0

I am trying to tune a SQL query which have IN clause in the query.

I tried replacing IN with Join and looked at the query plans.Both are looking similar in execution times, but the result is different.Can someone help me regarding this? I am using a shop database in pgadmin III. Thanks in advance. ORIGINAL QUERY:

SELECT person.id
FROM   SHOP.person
WHERE  person.id IN (SELECT personid
                     FROM   SHOP.contactperson
                     WHERE  companyid = 5); 

to

SELECT person.id
FROM   SHOP.person
       JOIN SHOP.contactperson
         ON person.id = contactperson.id
WHERE  contactperson.companyid = 5; 

EDITED: NOW THIS QUERY RETURNS CORRECT RESULTS:

SELECT person.id
FROM   SHOP.person
       JOIN SHOP.contactperson
         ON person.id = contactperson.personid
WHERE  contactperson.companyid = 5;

I was using contactperson.id instead of contactperson.id, and when I change it to the correct query it gave me correct results.

4
  • 2
    Performance tuning is highly vendor-specific - we need to know what concrete database (and which version) you're using. SQL is just the query language - used by the vast majority of relational database systems..... Commented Jan 5, 2014 at 14:56
  • @marc_s its a shop database, and I am using it in the pgadmin III. Commented Jan 5, 2014 at 14:57
  • 1
    Please show your table structures including indexes and the query plans. Commented Jan 5, 2014 at 15:03
  • It was Darhazer that noticed that. Not me! Commented Jan 5, 2014 at 15:07

2 Answers 2

2
SELECT pe.id
FROM   SHOP.person pe
WHERE  EXISTS (
   SELECT *     
   FROM   SHOP.contactperson cp
   WHERE cp.personid = pe.id
   AND  cp.companyid = 5
   ); 
Sign up to request clarification or add additional context in comments.

2 Comments

I have checked the execution plans for your suggested query and query suggested by Darhazer they are Identical. In what situation this query can perform better then the other solution suggested by Darhazer ???
They are different. If there is an 1:N relation between person and contactperson (which I expect, but you did not ahow us the datamodel) , Darhazer's query will yield more than one row per person, and mine exactly one.
1

Your join clause is not using the same fields as your original query. You should use personid from the contactperson table.

SELECT person.id
FROM SHOP.person 
Join SHOP.contactperson
ON person.id = contactperson.personid 
WHERE contactperson.companyid = 5;

1 Comment

This can still return different results if contactperson.personid is not unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.