Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an index on a boolean field

I have a Rails model with a boolean field that I search on (I use a scope that finds all instances where the field is set to true). I'm using Postgres.

My instinct is to add an index on the boolean field. Is that good practice, or is there something in Postgres that makes an index on a boolean field unnecessary?

like image 805
bevanb Avatar asked Sep 22 '12 00:09

bevanb


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.

How do you add a Boolean value to a table?

Since MySQL always use TINYINT as Boolean, we can also insert any integer values into the Boolean column. Execute the following statement: Mysql> INSERT INTO student(name, pass) VALUES('Miller',2);

How do I add a Boolean field in MySQL?

You can use tinyint(1) or bool or boolean. All are synonym. If you use bool or boolean datatype, then it nternally change into tinyint(1). In PHP, the value 0 represents false and 1 represents true.


2 Answers

No, you can index a boolean field if you'll be filtering by it. That's a perfectly reasonable thing to do, although as with all indexes, PostgreSQL may choose to ignore it if it won't exclude enough of the table -- an index scan plus a ton of row fetches may be more expensive than a sequential scan -- which may or may not affect you depending on the values in that column.

You should also be aware that PostgreSQL lets you put conditions on indexes, which I often find useful with boolean fields. (See Partial Indexes for details.) If you'll be commonly filtering or sorting within that scope, you might be best served by something like CREATE INDEX ... ON table (some_field) WHERE boolean_field.

like image 72
willglynn Avatar answered Sep 24 '22 05:09

willglynn


To create the partial index in a Rails migration, you would do this. In this example, the model is Product and the column is featured.

class AddFeaturedOnProducts < ActiveRecord::Migration   def change     add_index(:products, :featured, where: "featured")   end end 
like image 21
Mark Swardstrom Avatar answered Sep 23 '22 05:09

Mark Swardstrom