If I execute a query like this:
SELECT eid
FROM entidades e
WHERE distrito IN ( SELECT id FROM distritos WHERE distrito_t LIKE '%lisboa%' )
or
SELECT eid
FROM entidades e
WHERE concelho IN ( SELECT id FROM concelho WHERE concelho_t LIKE '%lisboa%' )
my indexes on distrito
or concelho
are being used.
For any of the queries stated above, the output of explain analyze will be something like this:
----------------------------------------------------------------------
Nested Loop (cost=239.36..23453.18 rows=12605 width=4) (actual time=29.995..790.191 rows=100602 loops=1)
-> HashAggregate (cost=1.38..1.39 rows=1 width=12) (actual time=0.081..0.085 rows=1 loops=1)
-> Seq Scan on distritos (cost=0.00..1.38 rows=1 width=12) (actual time=0.058..0.068 rows=1 loops=1)
Filter: ((distrito_t)::text ~~ '%lisboa%'::text)
-> Bitmap Heap Scan on entidades e (cost=237.98..23294.23 rows=12605 width=7) (actual time=29.892..389.767 rows=100602 loops=1)
Recheck Cond: (e.distrito = distritos.id)
-> Bitmap Index Scan on idx_t_ent_dis (cost=0.00..234.83 rows=12605 width=0) (actual time=26.787..26.787 rows=100602 loops=1)
Index Cond: (e.distrito = distritos.id)
However, for the following query, indexes are not used at all...
SELECT eid
FROM entidades e
WHERE concelho IN ( SELECT id FROM concelho WHERE concelho_t LIKE '%lisboa%' )
OR distrito IN ( SELECT id FROM distritos WHERE distrito_t LIKE '%lisboa%' )
----------------------------------------------------------------------
Seq Scan on entidades e (cost=10.25..34862.71 rows=283623 width=4) (actual time=0.600..761.876 rows=100604 loops=1)
Filter: ((hashed SubPlan 1) OR (hashed SubPlan 2))
SubPlan 1
-> Seq Scan on distritos (cost=0.00..1.38 rows=1 width=12) (actual time=0.083..0.093 rows=1 loops=1)
Filter: ((distrito_t)::text ~~ '%lisboa%'::text)
SubPlan 2
-> Seq Scan on concelhos (cost=0.00..8.86 rows=3 width=5) (actual time=0.173..0.258 rows=1 loops=1)
Filter: ((concelho_t)::text ~~ '%lisboa%'::text)
How can I create an index that will be used by the previous query?
According to this documentation it is possible...
But I'm probably not searching for the right thing since I can't find any example at all...
update: added explain output for both query types...