Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient Way to Create an Index in Postgres

People also ask

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.

What is the most common index type used in PostgreSQL?

The most common and widely used index type is the B-tree index. This is the default index type for the CREATE INDEX command, unless you explicitly mention the type during index creation.

How long does it take to create an index Postgres?

The index creation takes about 2 hours, which is really not useful. Is there any way I could speed up the index creation? Probably it's not better to set the index before data import, as this will slow down the import?

Are unique indexes faster?

A unique index guarantees that the table won't have more than one row with the same value. It's advantageous to create unique indexes for two reasons: data integrity and performance. Lookups on a unique index are generally very fast.


Your observation is correct - it is much more efficient to load data first and only then create index. Reason for this is that index updates during insert are expensive. If you create index after all data is there, it is much faster.

It goes even further - if you need to import large amount of data into existing indexed table, it is often more efficient to drop existing index first, import the data, and then re-create index again.

One downside of creating index after importing is that table must be locked, and that may take long time (it will not be locked in opposite scenario). But, in PostgreSQL 8.2 and later, you can use CREATE INDEX CONCURRENTLY, which does not lock table during indexing (with some caveats).