I have heard joins should be preferred over nested queries. Is it true in general? Or there might be scenarios where one would be faster than other:
for e.g. which is more efficient way to write a query?:
Select emp.salary
from employee emp
where emp.id = (select s.id from sap s where s.id = 111)
OR
Select emp.salary
from employee emp
INNER JOIN sap s ON emp.id = s.id
WHERE s.id = 111
It depends on the requirements, and the data.
Using a JOIN risks duplicating the information in the resultset for the parent table if there are more than one child records related to it, because a JOIN returns the rows that match. Which means if you want unique values from the parent table while using JOINs, you need to look at using either
DISTINCTor aGROUP BYclause. But none of this is a concern if a subquery is used.Also, subqueries are not all the same. There’s the straight evaluation, like your example:
…and the IN clause:
…which will match any of the value(s) returned by the subquery when the straight evaluation will throw an error if
s.idreturns more than one value. But there’s also theEXISTSclause…The EXISTS is different in that:
SELECT 1/0, which should trigger a divide-by-zero error but won’t