Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subselect vs outer join

Consider the following 2 queries:

select tblA.a,tblA.b,tblA.c,tblA.d
from tblA
where tblA.a not in (select tblB.a from tblB)

select tblA.a,tblA.b,tblA.c,tblA.d
from tblA left outer join tblB
on tblA.a = tblB.a where tblB.a is null

Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.

like image 397
shsteimer Avatar asked Sep 06 '08 13:09

shsteimer


People also ask

Which one is better subquery or join?

The advantage of a join includes that it executes faster. The retrieval time of the query using joins almost always will be faster than that of a subquery. By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query.

What is faster a correlated subquery or an inner join?

"Correlated subqueries" are faster than Normal joins.

When should you use a subquery?

Use subqueries when the result that you want requires more than one query and each subquery provides a subset of the table involved in the query. If a membership question is asked, then a subquery is usually used.

Can we use subquery in joins?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.


1 Answers

RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases.

I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity.

like image 73
Tom Avatar answered Sep 21 '22 12:09

Tom