Why is Postgres doing a Hash in this query?

Posted by Claudiu on Stack Overflow See other posts from Stack Overflow or by Claudiu
Published on 2010-06-17T20:38:54Z Indexed on 2010/06/17 20:43 UTC
Read the original article Hit count: 179

I have two tables: A and P. I want to get information out of all rows in A whose id is in a temporary table I created, tmp_ids. However, there is additional information about A in the P table, foo, and I want to get this info as well. I have the following query:

SELECT A.H_id AS hid,
       A.id AS aid,
       P.foo, A.pos, A.size
FROM tmp_ids, P, A
WHERE tmp_ids.id = A.H_id
  AND P.id = A.P_id

I noticed it going slowly, and when I asked Postgres to explain, I noticed that it combines tmp_ids with an index on A I created for H_id with a nested loop. However, it hashes all of P before doing a Hash join with the result of the first merge. P is quite large and I think this is what's taking all the time. Why would it create a hash there? P.id is P's primary key, and A.P_id has an index of its own.

© Stack Overflow or respective owner

Related posts about sql

Related posts about optimization