Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Create index for boolean column

I have a table that has one boolean column.

productid integer isactive boolean 

When I execute the query

SELECT productid        FROM      product       WHERE ispublish     LIMIT 15 OFFSET  0 

enter image description here

After that, I created an index for the ispublish column:

CREATE INDEX idx_product_ispublish ON product USING btree (ispublish) 

and re-execute

SELECT productid           FROM         product          WHERE ispublish        LIMIT 15 OFFSET  0 

The result:

enter image description here

=> No difference

I've been tried the following, but the results are the same:

CREATE INDEX idx_product_ispublish ON product USING btree (ispublish)  CREATE INDEX idx_product_ispublish ON product USING btree (ispublish)  CREATE INDEX idx_product_ispublish ON product (ispublish) WHERE ispublish is TRUE 

Who can explain that to me?

like image 764
Văn Duy Nguyễn Avatar asked Mar 23 '17 10:03

Văn Duy Nguyễn


People also ask

Can you index a Boolean?

The Boolean values like True & false and 1&0 can be used as indexes in panda dataframe. They can help us filter out the required records. In the below exampels we will see different methods that can be used to carry out the Boolean indexing operations.

Can we create index on primary key column in PostgreSQL?

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.


1 Answers

PostgreSQL will use an index only if it thinks it will be cheaper that way. An index on a boolean column, which can only take two possible values, will almost never be used, because it is cheaper to sequentially read the whole table than to use random I/O on the index and the table if a high percantage of the table has to be retrieved.

An index on a boolean column is only useful

  1. in data warehouse scenarios, where it can be combined with other indexes via a bitmap index scan.

  2. if only a small fraction of the table has the value TRUE (or FALSE for that matter). In this case it is best to create a partial index like

    CREATE INDEX ON mytab((1)) WHERE boolcolumn; 
like image 162
Laurenz Albe Avatar answered Oct 18 '22 19:10

Laurenz Albe