I have a table with below columns in PostgreSQL.
id,
location,
store,
flag1,
flag2
Here id, location, store are contributing to Primary Key. So by default postgreSQL creates an index on it.
I have created two more index apart from primary key index as below :
- id
- location, id
Now when I run the below query :
EXPLAIN ANALYZE
SELECT *
FROM my_table
WHERE location = '1' AND id = '1';
It should have used the index with location, id, but it uses primary key index.
Now when I run below query, it uses id index, which is expected.
EXPLAIN ANALYZE
SELECT *
FROM my_table
WHERE id = '1';
I am not sure on how can I force the indexing or the behaviour of PostgreSQL is correct & efficient one. On paper, it looks like location, id would be better choice for the query.
Can some help on the issue/doubt I have ?
Also if this is the expected behaviour, can you provide some query which will use location,id index ?
WHERE WHERE location = '1' AND id = '1';is identical toWHERE ID = '1' AND location = '1';Which would explain why a primary key ofid, location, storeis given precedence.