DBMS 5
DBMS 5
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.
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);
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 :
With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query. A correlated subquery, however, executes
once for each candidate row considered by the outer query. In other words, the inner
query is driven by the outer query.
CORRELATED UPDATE :
CORRELATED DELETE :
The following query finds employees whose salary is greater than the average salary of all
employees:
SELECT
employee_id,
first_name,
last_name,
salary
FROM
employees
WHERE
salary > (SELECT
AVG(salary)
FROM
employees);
SELECT
employee_id,
first_name,
last_name,
salary,
department_id
FROM
employees e
WHERE
salary > (SELECT
AVG(salary)
FROM
employees
WHERE
department_id = e.department_id)
ORDER BY
department_id ,
first_name ,
last_name;
SELECT
employee_id,
first_name,
last_name
FROM
employees e
WHERE
NOT EXISTS( SELECT
*
FROM
dependents d
WHERE
d.employee_id = e.employee_id)
ORDER BY first_name ,
last_name;
Using corelated subquery we obtain second highest , third highest and fourth highest
salary from the empl table.
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
Employee table
Department table
Manager table
Project table
Inner Join:
Left Join:
Right Join:
Full Join: