Practical - 8
Practical - 8
Practical No : 8
A correlated subquery is evaluated once for each row processed by the parent
statement. The parent statement can be a SELECT, UPDATE, or DELETE
statement.
A correlated subquery is one way of reading every row in a table and comparing
values in each row against related data. It is used whenever a subquery must return
a different result or set of results for each candidate row considered by the main
query. In other words, you can use a correlated subquery to answer a multipart
question whose answer depends on the value in each row processed by the parent
statement.
Nested Subqueries Versus Correlated Subqueries :
Nested subquery: The inner SELECT query runs first and executes once.
Correlated subqueries: Executes once for each candidate row considered by the
outer query.
The inner query executes for every row because outer.department_id is different
for all.
CORRELATED UPDATE :
UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column =
alias2.column);
Use a correlated subquery to update rows in one table based on rows from another
table.
CORRELATED DELETE :
DELETE FROM table1 alias1
WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from
another table.
Examples:
select p.last_name, p.department_id from employees p where
p.salary < (select avg(s.salary) from employees s where
s.department_id=p.department_id)
The flow of execution is as follows:
1. Start at the first row of the EMPLOYEES table.
2. Read the DEPARTMENT_ID and SALARY of the current row.
3. Run the subquery using the DEPARTMENT_ID from step 2
4. Compare the result of step 3 with the SALARY from step 2, and return the
row if the SALARY is less than the result.
5. Advance to the next row in the EMPLOYEES table.
6. Repeat from step 2.
Exercise
1. Write a query to determine who earns more than Mr. Lex.
2. Write a query find the job with the highest average salary.
3. Write a query to print employee id along with their manager id.
4. Write a query to print employees name who earns more than that of
their managers.
5. Write a query to print the name of employee who earns more than
that of their department’s average.
6. Write a query to print the name and id of those department whose
total no employee is greater than at least one of the departments.
7. Write a query to print the name of employee who draw second lowest
salary in the company.
8. Write a query to print the name of employee who draw second lowest
salary in their respective departments.