Re: Correct syntax to create partial index on a boolean column

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: Mike Christensen <mike(at)kitchenpc(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Correct syntax to create partial index on a boolean column
Date: 2011-12-15 07:53:37
Message-ID: B78F75C6-663C-4CC2-8AA9-67CBCCB7E70C@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 15 Dec 2011, at 5:43, Mike Christensen wrote:

> For the boolean column Foo in Table1, if I want to index all values of
> TRUE, is this syntax correct?
>
> CREATE INDEX IDX_MyIndex ON Table1(Foo) WHERE Foo;
>
> The query:
>
> SELECT * FROM Table1 WHERE Foo;
>
> should use the index, and:
>
> SELECT * FROM Table1 WHERE NOT Foo;
>
> should not, correct?

Correct, but...
That's not a particularly useful index to create. That index just contains values of true where the associated column equals true - you're storing the same information twice.

It's generally more useful to index a column with values that you're likely to be interested in for limiting the result set further or for sorting or some-such, as long as the operation performed benefits from using an index.

From your later example, for instance:

SELECT RecipeId from RecipeMetadata where diet_glutenfree;

If you plan to use this query in a join, an index like this would be more useful:

CREATE INDEX recipemetadata_recipeid_glutenfree_idx ON RecipeMetadata(RecipeId) WHERE diet_glutenfree;

That's a bit similar to creating an index on (RecipeId, diet_glutenfree), except that the latter also contains entries that are not gluten-free of course.

Alban Hertroys

--
The scale of a problem often equals the size of an ego.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Albe Laurenz 2011-12-15 08:26:47 Re: Locking Tables & Backup Inquiry
Previous Message Mike Christensen 2011-12-15 06:57:35 Re: Correct syntax to create partial index on a boolean column