2

We have a table users (userid, username, category, pincode) in postgresql

If we create indexes like:

  1. create index category_idx(category) on users;
  2. create index category_pincode_idx(category, pincode) on users;

and query the table users as:

select * from users where category = somevalue; 

which index will be applied?

6
  • 1
    The first index is redundant. Any query that can use the first index also can use the second. You might also want to read this: postgresql.org/docs/current/static/indexes-examine.html Commented May 3, 2013 at 8:22
  • One more thing i would like to ask: If there is a table users (userid, username, category, pincode) whose primary key is (userid, category, pincode), then it is required/not to create an index on those primary key columns separately/as a whole. Commented May 3, 2013 at 9:18
  • When you define a primary key, Postgres automatically creates an unique index for that: postgresql.org/docs/current/static/indexes-unique.html Commented May 3, 2013 at 9:19
  • So, it means there is no need to create an index explicitly on column pincode separately if its a part of primary key. Commented May 3, 2013 at 9:23
  • That's not what I said. If you have a query that has a condition only on pincode, it might make sense. Please do read the chapter about indexes in the manual Commented May 3, 2013 at 9:24

1 Answer 1

3

Executing the following statement will reveal which index the execution planner will pick depending on the current data set:

explain select * from users where category = somevalue;

Please be advised that the planner might even chose to not use the index if the amount of data does not warrant the use of an index because a full table scan over very few rows might be quicker.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.