Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a subquery cause a scan when a static list does not?

Tags:

sql

sqlite

I've got a query containing a subquery which always causes a SCAN of a very large table resulting in poor query times.

This is the query I'm using:

SELECT PersonId 
  FROM person 
 WHERE PersonId IN (
                    SELECT PersonId 
                      FROM relationship 
                     WHERE RelatedToPersonId = 12270351721
                   );

The query plan is reported as:

SCAN TABLE person (~100000 rows)
EXECUTE LIST SUBQUERY 1
SEARCH TABLE relationship USING INDEX relationship_RelatedToPersonId_IDX (RelatedToPersonId=?) (~10 rows)

The same query with a static list (equivalent to the results of the subquery):

SELECT PersonId 
  FROM person 
 WHERE PersonId IN (12270351727,12270351730,12270367969,12387741400);

And the query plan for that:

SEARCH TABLE person USING COVERING INDEX sqlite_autoindex_person_1 (PersonId=?) (~5 rows)
EXECUTE LIST SUBQUERY 1

Why would the first query prompt a scan if the second does not?

like image 771
goto10 Avatar asked Oct 25 '11 19:10

goto10


2 Answers

Probably unmatched datatypes. Does person.PersonId and relationship.PersonId have the same data definition.

like image 136
Gary Thomann Avatar answered Sep 18 '22 08:09

Gary Thomann


The table has to be scanned because you're including another field (RelatedToPersonId) in the WHERE clause of your subquery. The list of PersonIDs can go directly to the index.

like image 40
dmogle Avatar answered Sep 20 '22 08:09

dmogle