3. OBJECTIVES
At the end of this module, students should be able
to:
1. Define sub-queries.
2. Know type of problems that sub-queries
can solve.
3. List the types of sub-queries
4. Write single row and multiple row sub-
queries.
4. SUB-QUERIES
A sub-query –also called a nested SELECT
statement- is defined as a query, within
another query.
It may appear in the WHERE clause, in the HAVING
clause, or in the FROM clause.
When placing a restriction on a query block,
we always specify the conditions for the
restriction in the WHERE clause.
6. Under certain conditions, you may need to
write a query to determine the WHERE condition.
7. EXERCISE:
Using a single SELECT statement, query the
employees table for those employees who
earn a salary below Nancy’s salary.
However, if you want to query for the details
of all the staff who earn a salary less than that
of Nancy you would use a sub-query for
Nancy’s salary, and the result in the WHERE
condition of our SELECT statement.
8. We have two types of sub-queries. The single
row sub-queries and the multiple row sub-
queries.
9. SINGLE ROW SUB_QUERIES
The single row sub-queries, would return only
one value, from the inner SELECT statement. In a
single row sub-query, the outer query,
contains a single row comparison operator,
like an equal to, equal to or greater than, or
less than.
11. This is a single row sub-query because the
inner SELECT statement will return only one value
and the outer SELECT statement uses a single
comparison operator to pick up that value.
12. MULTIPLE ROW SUB_QUERIES
A multiple row sub-query on the contrary
would return more than one row from the
inner SELECT statement.
The outer SELECT will therefore need a multiple
comparison operator like ANY, IN or ALL to pick the
multiple values returned by the inner query.
14. The Oracle server first takes the inner
query and searches for the DISTINCT values in
the salary of employees, with STORE CLERK as the
job_id.
It then places this numbers in the bracket
next to the ANY keyword. And that is what
gives us the result displayed, on the
previous screen.