Sub topic 1
Subqueries and Correlated Subqueries in Oracle SQL
Prerequisites
This chapter assumes you can write SELECT, WHERE, GROUP BY and joins between two tables. You should know aggregate functions such as AVG, COUNT and MAX, and you should have access to the Oracle HR sample schema with the EMPLOYEES and DEPARTMENTS tables.
What a subquery is
A subquery is a SELECT statement nested inside another statement. Oracle runs the inner query first, then uses its result in the outer query.
Single-row subqueries
A single-row subquery returns one value, and you compare it with a single-row operator such as =, > or <.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);If the inner query returns more than one row, Oracle raises ORA-01427 ("single-row subquery returns more than one row").
Multi-row subqueries: IN, ANY and ALL
A multi-row subquery returns a set of values. Use IN, ANY or ALL to compare against that set.
SELECT department_name
FROM departments
WHERE department_id IN (SELECT department_id
FROM employees
WHERE salary > 10000);ANY is true when the comparison holds for at least one value in the set. ALL is true only when it holds for every value.
SELECT last_name, salary
FROM employees
WHERE salary > ALL (SELECT salary
FROM employees
WHERE department_id = 30);Where subqueries can appear
Subqueries can appear in several clauses of a SELECT statement.
| Clause | Use |
|---|---|
| WHERE | Filter rows by a value or set from another query |
| HAVING | Filter groups by an aggregate computed in a subquery |
| FROM | Provide a derived table, called an inline view |
| SELECT | Return one computed value for each row |
Exercise
Write a query that lists the employees whose salary is greater than the salary of every employee in department 30. Which operator do you use, and why?
Show answer
Use ALL. The condition is salary > ALL (SELECT salary FROM employees WHERE department_id = 30), because the outer salary must exceed every value the subquery returns.