sql_sub_query
sql_sub_query
Follow
Manni Chopra
Sub Query :
If a Query that contains another Query, then the Query inside
the main Query is called a Sub Query and the main Query is
known as the parent Query.
In Oracle the Sub Query will executed on the prior basis and
the result will be available to the parent Query and then the
execution of the parent/main Query takes place. A Sub Query
can also be called a Nested/Inner Query. These Sub Queries
can be used with:
▪ WHERE Clause
▪ SELECT Clause
▪ FROM Clause
Common SQL Clauses for Subqueries :
• = Equals to
• > Greater than
• < Less than
• >= Greater than Equals to
• <= Less than Equals to
• <> Not Equals to
SELECT * FROM employees
WHERE salary = (SELECT MIN(salary) FROM employees);
• IN
• ANY
• ALL or EXISTS
Example :
SELECT e.first_name, e.salary
FROM employees e
WHERE salary IN ( SELECT MIN(e.salary)
FROM employees e
GROUP BY e.department_id);
3. Multiple Column Sub Query
Multiple Column Sub Queries are queries that return multiple
columns to the outer SQL query. It uses the IN operator for the
WHERE and HAVING clause.
SELECT e.department_id, e.job_id,e.salary
FROM employees e
WHERE (e.job_id, e.salary) IN ( SELECT e.job_id, e.salary
FROM employees e
WHERE e.department_id = 50) ;
SELECT e.first_name,e.salary
FROM employees e
WHERE e.manager_id in
( SELECT e.manager_id
FROM employees e
WHERE department_id in (select d.department_id
FROM departments d
WHERE d.department_name='Purchasing' ));
5. Correlated Sub Query
A Correlated Sub Query contains a reference to a table that
appears in the outer query. It is used for row by row
processing, in other words the Sub Query will execute row
by row for the parent query.
Manni Chopra
Follow me on Linkedin