Friday, May 2, 2014

What is the difference between sub-query & co-related sub query?

A sub query is executed once for the parent statement
whereas the correlated sub query is executed once for each
row of the parent query.
Sub Query:
Example:
 Select deptno, ename, sal from emp a  where sal  in (select sal from Grade  where sal_grade=’A’ or  sal_grade=’B’)
Co-Related Sun query:
Example:
Find all employees who earn more than the average salary in their department.
SELECT last-named, salary, department_id  FROM employees A
WHERE salary > (SELECT AVG (salary)
FROM employees B WHERE B.department_id =A.department_id
Group by B.department_id)


Sub-query
Co-related sub-query
A sub-query is executed once for the parent Query
Where as co-related sub-query is executed once for each row of the parent query.
Example:
Select * from emp where deptno in (select deptno from dept);
Example:
Select a.* from emp e where sal >= (select avg(sal) from emp a where a.deptno=e.deptno group by  a.deptno);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.