I'm starting to better understand PostgreSQL indexing, but I have a problem with the conditional expression OR, where I do not know how to optimize my indexes for a faster query.
I have 6 conditional expressions that when run individually seem small. Here is an example of cropped queries, including the estimated time of the query plan.
(NOTE: I did not output the actual query plans for these queries below to reduce complexity, but they all use nested loop left joins and index scans , as I would expect with proper indexing. If necessary, I can include query plans for a more meaningful answer.)
EXPLAIN ANALYZE SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions1) LIMIT 10; QUERY PLAN
My problem is that I want to join these 6 conditions together with OR operators, which makes each condition possible. My combined query looks something like this:
EXPLAIN ANALYZE SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions1 OR conditions2 OR conditions3 OR conditions4 OR conditions5 OR conditions 6) LIMIT 10;
Unfortunately, this leads to an increase in MASSIVE in terms of queries, which no longer uses my indexes (instead, you select hash left join rather than nested loop left join , and perform various sequence scans on the previously used index scans ).
Limit (cost=142.62..510755.78 rows=1 width=171) (actual time=30.591..30.986 rows=10 loops=1)
Is there anything special I need to know about indexing regarding OR-ed conditions that will improve my final query?
UPDATE If I use UNION for every single SELECT, this speeds up the query. However, does this prevent me from ordering my results if I want in the future? Here is what I did to speed up the query through UNION:
EXPLAIN ANALYZE SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions1) UNION SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions2) UNION SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions3) UNION SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions4) UNION SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions5) UNION SELECT t1.*, t2.*, t3.* FROM t1 LEFT JOIN t2 on t2.id = t1.t2_id LEFT JOIN t3 ON t3.id = t1.t3_id WHERE (conditions6) LIMIT 10; QUERY PLAN