Oracle Subqueries (Russian Dolls) πͺ
Mentor's Note: A subquery is just a query inside another query. Think of it like a "Helper question". You ask one question to get an answer, then use that answer to solve the main problem. π‘
π The Scenario: The Average Earner π°β
- The Problem: Who earns more than the average?
- Step 1 (Inner): Find the average salary.
- Step 2 (Outer): Find people whose salary > Step 1. β
π» 1. Basic Subqueryβ
The inner query runs once first.
SELECT first_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
π» 2. Correlated Subquery πβ
The inner query runs once for every row in the outer query. It's slower but much more powerful.
-- Scenario: Find employees who earn more than the average of THEIR department
SELECT emp_name, salary, dept_id
FROM employees E
WHERE salary > (
SELECT AVG(salary) FROM employees WHERE dept_id = E.dept_id
);
π» 3. EXISTS & NOT EXISTS πͺβ
Checks if any rows are returned. It doesn't care what is returned, just if it's there.
-- Find departments that have at least one employee
SELECT department_name FROM departments D
WHERE EXISTS (SELECT 1 FROM employees WHERE department_id = D.department_id);
π» 4. ANY, SOME, and ALLβ
Used to compare a single value against a list.
> ANY: Higher than the minimum in the list.> ALL: Higher than the maximum in the list.
-- Salary higher than ALL IT programmers
SELECT first_name FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE job_id = 'IT_PROG');
ποΈ Architect's Note: Performance - EXISTS vs IN π‘οΈβ
In old versions of Oracle, EXISTS was much faster than IN. In modern versions, the Oracle Optimizer is smart enough to turn an IN into an EXISTS automatically.
- The Architect's Secret:
EXISTSis still slightly better for large datasets because it uses Semi-Join logicβit stops as soon as it finds the first match!