Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine what type of index to use in Postgres?

I have a Postgres database that has 2 columns that are not primary keys (nor can be), but are searched on a lot and are compared for equality to 2 columns in other tables.

I believe this is a perfect case for adding an index to my tables. I have never used indexing on a database before so I am trying to learn the proper way of doing this.

I have learned that there are multiple types of indexing I can pick from. How do I determine what method will be the most efficient for my database? Also would the proper method be to create a single index that covers both columns?

like image 300
Kellenjb Avatar asked Dec 01 '10 16:12

Kellenjb


People also ask

How does Postgres decide which index to use?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.

Which index is best in PostgreSQL?

B-tree indexes B-tree is the default index in Postgres and is best used for specific value searches, scanning ranges, data sorting or pattern matching.

How do I choose a database index?

It is recommended to start indexing the table by creating a clustered index, that covers the column(s) called very frequently, which will convert it from the heap table to a sorted clustered table, then create the required non-clustered indexes that cover the remaining queries in the system.


2 Answers

Postgres support B-tree, R-tree, Hash, GiST and GIN indexing types. B-tree indexing is the most common and fits most common scenarios. This is the syntax:

CREATE INDEX idex_name ON table_name USING btree(column1, column2); 

Here is the createindex documentation and here is more info on different indextypes in postgres.

What type of index you should use depends on what types of operations you want to perform. If you simply want equality checking then hash index is the best. For most common operations(e.g. comparison, pattern matching) B-tree should be used. I have personally never used GiST or GIN indexing. ANY Guru out there?

The documentation describes all these types. They can help you better than me :)

Hope this helps.

like image 101
Max Avatar answered Oct 05 '22 23:10

Max


Try to understand the queryplanner as well, because this part of PostgreSQL has to work with your indexes. EXPLAIN ANALYZE will be essential to optimise your queries.

like image 45
Frank Heikens Avatar answered Oct 06 '22 00:10

Frank Heikens