Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can u please point out the difference
Self join & correlated query


Which one is better to use?

how to decide which is to be used?
Posted

Where did you learn these terms ? Do you know what they mean ? The answer, as always, is that it depends.

SQL
SELECT
   employee_number,
   name,
   (SELECT AVG(salary)
      FROM employees
      WHERE department = Bob.department) AS department_average
   FROM employees AS Bob;


The second select is a subquery.

A self join is where a table joins to itself. Both are expensive. Both have uses and are sometimes the right choice, depending on your situation. I almost never use either, I use CTEs, my article on those is here[^]. If you have a specific question, try posting the details of the specific SQL you're working on. If this is a general question, it has no real answer, the answer is to know the pitfalls and benefits of many approaches, and choosing the right approach for each task.
 
Share this answer
 
Comments
Maciej Los 29-Dec-13 7:48am    
+5!
Depends on your exact query.
But the general answer is that the query optimizer will realize that the correlated subquery can be exchanged with a join and will do so. And then it won't matter, it will only be a matter of syntax.
 
Share this answer
 
Comments
Maciej Los 29-Dec-13 7:48am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900