Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a case in SQL where a subquery is more efficient than a join?

Tags:

sql

join

subquery

I've seen people hypothetically say that there are cases when a subquery can be more efficient than a join but I have never actually seen a good example of this?

What would be a case when you would want to use a subquery over a join?

like image 281
ctrlShiftBryan Avatar asked Mar 21 '11 16:03

ctrlShiftBryan


2 Answers

The classic example is searching for rows in a table that do not have corresponding rows in another.

SELECT a.*
    FROM TableA a
    WHERE NOT EXISTS(SELECT NULL FROM TableB b WHERE b.parent_id = a.id)

is generally better than

SELECT a.* 
    FROM TableA a
        LEFT JOIN TableB b
            ON a.id = b.parent_id
    WHERE b.parent_id IS NULL

See also: Left outer join vs NOT EXISTS

like image 80
Joe Stefanelli Avatar answered Nov 17 '22 01:11

Joe Stefanelli


When using EXISTS with a sub-query the sub-query solution should be faster (compared to an outer join and checking for NULL), because the "evaluation" of the sub-query terminates as soon as the first row is returned.

My experience is that most of the time the query optimizer chooses the same plan anyway, so that there is no performance difference between both of them (at least with Oracle and PostgreSQL)

like image 45
a_horse_with_no_name Avatar answered Nov 17 '22 01:11

a_horse_with_no_name