Considering the following query:
select a.id from a
where
a.id in (select b.a_id from b where b.x='x1' and b.y='y1') and
a.id in (select b.a_id from b where b.x='x2' and b.y='y2')
order by a.date desc
limit 20
Which should be rewritable to that faster one:
select a.id from a inner join b as b1 on (a.id=b1.a_id) inner join b as b2 on (a.id=b2.a_id)
where
b1.x='x1' and b1.y='y1' and
b2.x='x2' and b2.y='y2'
order by a.date desc
limit 20
We would prefer not to rewrite our queries by changing our source code as it complicates a lot (especially when using Django).
Thus, we wonder when PostgreSQL collapses subqueries to joins and when not?
That is the simplified data model:
Table "public.a"
Column | Type | Modifiers
-------------------+------------------------+-------------------------------------------------------------
id | integer | not null default nextval('a_id_seq'::regclass)
date | date |
content | character varying(256) |
Indexes:
"a_pkey" PRIMARY KEY, btree (id)
"a_id_date" btree (id, date)
Referenced by:
TABLE "b" CONSTRAINT "a_id_refs_id_6e634433343d4435353" FOREIGN KEY (a_id) REFERENCES a(id) DEFERRABLE INITIALLY DEFERRED
Table "public.b"
Column | Type | Modifiers
----------+-----------+-----------
a_id | integer | not null
x | text | not null
y | text | not null
Indexes:
"b_x_y_a_id" UNIQUE CONSTRAINT, btree (x, y, a_id)
Foreign-key constraints:
"a_id_refs_id_6e634433343d4435353" FOREIGN KEY (a_id) REFERENCES a(id) DEFERRABLE INITIALLY DEFERRED
- a has 7 million rows
- b has 70 million rows
- cardinality of b.x = ~100
- cardinality of b.y = ~100000
- cardinality of b.x, b.y = ~150000
- imagine tables c, d and e that have the same structure as b and could be used additionally to further reduce the resulting a.ids
Versions of PostgreSQL, we tested the queries.
PostgreSQL 9.2.7 on x86_64-suse-linux-gnu, compiled by gcc (SUSE Linux) 4.7.2 20130108 [gcc-4_7-branch revision 195012], 64-bit
PostgreSQL 9.4beta1 on x86_64-suse-linux-gnu, compiled by gcc (SUSE Linux) 4.7.2 20130108 [gcc-4_7-branch revision 195012], 64-bit
Query Plans (with empty file cache and mem cache):
Your last comment nails the reason, I think: The two queries are not equivalent unless a unique constraint kicks in to make them equivalent.
Example of an equivalent schema:
Equivalent offending data using that schema:
Rows using two IN clauses:
Rows using two joins:
I see you've a unique constraint on b (a_id, x, y) already, though. Perhaps highlight the issue to the Postgres performance list to get the reason why it's not collapsed in your particular case -- or at least not generating the exact same plan.