0

Given a table of stores (~10k records) and a table of schedules(~200k records), I am trying to create and index for the planner to use, but it ignores it so far.

select * from stores str
   inner join schedule sch on sch.store_id = str.store_id
where sch.open is true and sch.tables > 0

create index sch_open_tables_idx on schedule(open, tables) where open is true and tables > 0

Is there a correct way of doing this?

3
  • Could you include the log/result/test that led you to think the index is being ignored and in what query is it being ignored? Commented Feb 14, 2017 at 15:16
  • 1
    Please read postgresql-performance then edit your question and provide the missing information. Commented Feb 14, 2017 at 15:17
  • 1
    At least, you don't need the open column in the index (it will always be true), but store_id may be helpful (as the first column in that index). -- Also, you could just use where sch.open in both your query and index, is true is not necessary (but won't hurt either, nullability doesn't change things here; it just feels noise). Commented Feb 14, 2017 at 16:11

2 Answers 2

1

The index you need is:

create index sch_open_tables_id on schedule(store_id)
where open and tables > 0;

store_id is probably the primary key on the stores table so there is already an index on it. If not:

create index store_id on stores(store_id);
Sign up to request clarification or add additional context in comments.

Comments

0

these are 2 tables, so use 2 indices - one for each, anyway such small tables shouldn't require partial indices

EXPLAIN select * from stores str
   inner join schedule sch USING (store_id)
where sch.open is true and tables > 0;

create index sch_open_idx on schedule(store_id) where open is true;
create index str_tables_idx on stores(store_id) where tables > 0;

vacuum analyze stores;
vacuum analyze schedule;

EXPLAIN select * from stores str
   inner join schedule sch USING (store_id)
where sch.open is true and tables > 0;

2 Comments

Ok but why do you think the column tables belongs to stores?
Column tables belong to schedule.

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.