Tuesday, April 27, 2010

SQL Subqueries vs Joins


In most cases Joins are faster than sub-queries and it is very rare for a sub-query to be faster.
In Joins RDBMS can create an execution plan that is better for your query and can predict what data should be loaded to be processed and save time, unlike the sub-query where it will run all the queries and load all their data to do the processing.
The good thing in sub-queries is that they are more readable than Joins, that's why most new SQL people prefer them; it is the easy way; but when it comes to performance, Joins are better in most cases even though they are not hard to read too.



The Subquery way: 
SELECT * FROM Persons WHERE (P_Id NOT IN(SELECT DISTINCT P_Id FROM orders))
The above subquery is equivalent to a left excluding Join: 
SELECT * FROM Persons 
LEFT JOIN Orders on Persons.P_Id = Orders.P_Id
WHERE Orders.P_Id IS NULL

No comments :

Post a Comment