PostgreSQL & PHP Tutorials - Multicolumn Indexes

PostgreSQL »  How to index a database
PostgreSQL »  Starting Out »  How to index a database

Posted By Chris Smith Posted on 15 Feb 2006, 08:17 PM
Viewing page 3 of 4
« | Back | Next | »

We could create an index like this:

CREATE INDEX news_cats ON newsitem_categories(newsid, categoryid);

However, doing this limits some ways the index can be used.

A query against that table that users both 'newsid' and 'categoryid' will be able to use this index.

A query against that table that only gets the 'newsid' will be able to use the index.

A query against that table that only gets the 'categoryid' will not be able to use the index.


For a table like this:

CREATE TABLE example (
a int,
b int,
c int
);

This index:
CREATE INDEX example_index ON example(a,b,c);

It will be used when you check against 'a'.

It will be used when you check against 'a' and 'b'.

It will be used when you check against 'a', 'b' and 'c'.

It will not be used if you check against 'b' and 'c', or if you only check 'b' or you only check 'c'.

It will be used when you check against 'a' and 'c' but only for the 'a' column - it won't be used to check the 'c' column as well.


A query against 'a' OR 'b' like this:
SELECT a,b,c FROM example where a=1 OR b=2;

will only be able to use the index to check the 'a' column as well - it won't be able to use it to check the 'b' column.

Multicolumn indexes have quite specific uses, so check their use carefully.
Avg Rating: 5
Vote Count: 14


              

  New Reply


"Now that we've seen when we should use indexes, let's look at when we shouldn't use them."

read the first line ;) seen when we, look at when we.

i think you mean seen why we, look at when we.

[ Editor's note - Fixed, thanks! ]
Joseph Crawford 09 Jun 2006 Reply


Want to post a comment? Fill in the details below.

Your Name  : 
Your Email  : 
Your Website  : 
Spam Check! Please answer this question  : 6 + 6 =
Comment