Using the sample salaries 90000, 60000, 55000, 50000, 50000, 30000, 28000, 25000, 22000, 20000, find the second highest salary in two different ways, then the 4th highest distinct salary.
A sub-query is a SELECT nested inside another statement. Scalar, row and table sub-queries feed comparisons, IN, EXISTS, ANY/ALL, FROM and SELECT; correlated sub-queries re-run for every outer row. Second-highest salary, above-average earners and 'works on all projects' are exam staples.
SELECT 1, SELECT * and SELECT NULL all work).A sub-query (nested query, inner query) is a SELECT enclosed in parentheses inside another SQL statement, the outer query. A non-correlated sub-query runs once and its result is substituted into the outer query: SELECT ename, salary FROM emp WHERE salary > (SELECT AVG(salary) FROM emp) first computes the average (43000) and then returns Anil, Bindu, Charles, Divya and Eby.
| Kind | Returns | Typical use | Sample-data example |
|---|---|---|---|
| Scalar | 1 row × 1 column | With = < > etc., in SELECT, in SET of UPDATE | (SELECT AVG(salary) FROM emp) → 43000 |
| Row | 1 row × n columns | Row comparison (a, b) = (…) | (job, dept_id) = (SELECT job, dept_id FROM emp WHERE ename = 'Divya') → Divya, Eby |
| Column (multi-row) | n rows × 1 column | IN, NOT IN, ANY, ALL | dept_id IN (SELECT dept_id FROM dept WHERE location = 'Kochi') |
| Table | n rows × m columns | EXISTS, FROM (derived table), WITH | FROM (SELECT dept_id, AVG(salary) AS avg_sal FROM emp GROUP BY dept_id) d |
Sub-queries may appear in WHERE and HAVING (the classic place), in FROM, in the SELECT list, and inside INSERT, UPDATE and DELETE (DELETE FROM works_on WHERE proj_id IN (SELECT proj_id FROM project WHERE budget < 350000)). Most systems forbid ORDER BY inside a sub-query used with IN, because order is meaningless there.
A comparison operator needs a single value on each side. WHERE salary = (SELECT salary FROM emp WHERE dept_id = 20) is wrong because department 20 has four salaries: Oracle stops with 'ORA-01427: single-row subquery returns more than one row', SQL Server and PostgreSQL raise similar errors — and SQLite silently uses the first row (60000) and returns Bindu, hiding the bug. For a set of values use IN: salary IN (SELECT salary FROM emp WHERE dept_id = 20) returns Bindu, Divya, Eby and Indu.
IN is a shorthand for a chain of OR-ed equalities and NOT IN for a chain of AND-ed inequalities. That expansion explains the most famous trap in SQL: if the sub-query's result contains a NULL, NOT IN can never be TRUE.
SELECT dname FROM dept
WHERE dept_id NOT IN (SELECT dept_id FROM emp WHERE dept_id IS NOT NULL);
SELECT dname FROM dept d
WHERE NOT EXISTS (SELECT 1 FROM emp e WHERE e.dept_id = d.dept_id);emp_id NOT IN (SELECT manager_id FROM emp) — 'employees who manage nobody' — because Anil's manager_id is NULL: the query returns nothing instead of Eby, Fathima, Gopal, Hari, Indu and Jose. IN does not have this problem (a NULL just never matches).x op ANY (S) (SOME is a synonym) is TRUE if the comparison holds for at least one value of S; x op ALL (S) is TRUE if it holds for every value. Department 30 earns {55000, 30000, 28000}, so salary > ALL (…dept 30…) means 'more than 55000' (Anil, Bindu) and salary > ANY (…dept 30…) means 'more than 28000' (Anil, Bindu, Charles, Divya, Eby, Fathima).
| Expression | Equivalent (non-empty S without NULLs) | Meaning |
|---|---|---|
x = ANY (S) | x IN (S) | equal to some value |
x <> ALL (S) | x NOT IN (S) | different from every value |
x > ANY (S) | x > (SELECT MIN …) | greater than the smallest |
x > ALL (S) | x > (SELECT MAX …) | greater than the largest |
x < ANY (S) | x < (SELECT MAX …) | smaller than the largest |
x < ALL (S) | x < (SELECT MIN …) | smaller than the smallest |
Edge cases separate the equivalences. Over an empty S, x > ALL (S) is TRUE for every row (nothing to beat) and x > ANY (S) is FALSE, whereas x > (SELECT MAX(salary) … WHERE dept_id = 40) compares with NULL and returns no rows. If S contains a NULL, > ALL can never be TRUE, while MAX simply ignores the NULL.
EXISTS (sub-query) is TRUE if the sub-query returns at least one row and FALSE otherwise — never UNKNOWN. What the sub-query selects is irrelevant, so SELECT 1, SELECT * and even SELECT NULL behave identically. EXISTS is almost always used with a correlated sub-query that links back to the outer row.
-- departments with at least one employee earning more than 50000
SELECT dname FROM dept d
WHERE EXISTS (SELECT 1 FROM emp e WHERE e.dept_id = d.dept_id AND e.salary > 50000);
-- Accounts, Research, Sales
-- employees with no project assignment (anti-join)
SELECT ename FROM emp e
WHERE NOT EXISTS (SELECT 1 FROM works_on w WHERE w.emp_id = e.emp_id);
-- Anil, Charles, Indu, Jose
-- employees on project 2 (semi-join)
SELECT ename FROM emp e
WHERE EXISTS (SELECT NULL FROM works_on w WHERE w.emp_id = e.emp_id AND w.proj_id = 2);
-- Bindu, Divya, EbyEXISTS implements a semi-join (keep outer rows that have a match, without duplicating them) and NOT EXISTS an anti-join (keep outer rows that have no match). Because EXISTS stops at the first matching row and handles NULLs cleanly, it is usually preferred over IN/NOT IN for large or nullable sub-query results — though modern optimizers often produce the same plan for both.
A sub-query in FROM is a derived table (Oracle: inline view). It is computed first and then treated like a table, so it must be given an alias in most products (… ) d). A scalar sub-query in the SELECT list computes one value per output row.
-- derived table: each above-average employee with the department average
SELECT e.ename, e.salary, ROUND(d.avg_sal, 2) AS dept_avg
FROM emp e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal FROM emp GROUP BY dept_id) d
ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal; -- Anil 56000, Bindu 45000, Charles 37666.67, Divya, Eby
-- scalar sub-query in SELECT: number of projects per employee
SELECT ename,
(SELECT COUNT(*) FROM works_on w WHERE w.emp_id = e.emp_id) AS projects
FROM emp e; -- Bindu 4, Eby 3, Divya 2, … Anil 0
-- the same derived table, named with WITH (common table expression, SQL:1999)
WITH dept_avg AS (SELECT dept_id, AVG(salary) AS avg_sal FROM emp GROUP BY dept_id)
SELECT e.ename FROM emp e JOIN dept_avg a ON a.dept_id = e.dept_id WHERE e.salary > a.avg_sal;WITH RECURSIVE chain(emp_id, ename, lvl) AS (
SELECT emp_id, ename, 0 FROM emp WHERE emp_id = 101 -- anchor: Anil
UNION ALL
SELECT e.emp_id, e.ename, c.lvl + 1
FROM emp e JOIN chain c ON e.manager_id = c.emp_id -- step: direct reports
)
SELECT * FROM chain ORDER BY lvl, emp_id;
-- level 1: Bindu, Charles, Hari level 2: Divya, Eby, Fathima, Gopal, Jose level 3: Indu-- 1. the maximum below the maximum
SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp);
-- 2. sort distinct values and skip one (Oracle 12c: OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY)
SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET 1;
-- 3. correlated count: exactly one distinct salary is higher
SELECT DISTINCT salary FROM emp e1
WHERE 1 = (SELECT COUNT(DISTINCT salary) FROM emp e2 WHERE e2.salary > e1.salary);
-- 4. window function
SELECT salary FROM (SELECT DISTINCT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM emp)
WHERE r = 2;Methods 2–4 generalise to the N-th highest salary: OFFSET N − 1, a correlated count equal to N − 1, or DENSE_RANK() = N. On the sample data the 3rd highest is 55000 and the 4th highest is 50000 (shared by Divya and Eby — which is why DISTINCT matters; without it, OFFSET would count Eby's 50000 as a separate place).
| Problem | Solution sketch | Result |
|---|---|---|
| Highest-paid employee in each department | WHERE salary = (SELECT MAX(salary) FROM emp e2 WHERE e2.dept_id = e1.dept_id) | Anil (10), Bindu (20), Charles (30) |
| Departments with no employees | NOT EXISTS (SELECT 1 FROM emp e WHERE e.dept_id = d.dept_id) | Operations |
| Duplicate salaries | SELECT salary FROM emp GROUP BY salary HAVING COUNT(*) > 1 | 50000 |
| Projects above the average budget | WHERE budget > (SELECT AVG(budget) FROM project) (average 525000) | AI Lab (900000) |
| Employees working on all projects | Double NOT EXISTS (below) or GROUP BY emp_id HAVING COUNT(DISTINCT proj_id) = (SELECT COUNT(*) FROM project) | Bindu |
SELECT e.ename
FROM emp e
WHERE NOT EXISTS ( -- there is no project p ...
SELECT * FROM project p
WHERE NOT EXISTS ( -- ... that e does not work on
SELECT * FROM works_on w
WHERE w.emp_id = e.emp_id AND w.proj_id = p.proj_id));
-- BinduMany sub-queries can be rewritten as joins and vice versa; the results match if you take care of duplicates and NULLs. Knowing the rewrites helps both in reading MCQ options and in tuning slow queries.
| Sub-query form | Join form | Watch out for |
|---|---|---|
WHERE dept_id IN (SELECT dept_id FROM dept WHERE location = 'Kochi') | SELECT DISTINCT e.ename FROM emp e JOIN dept d ON d.dept_id = e.dept_id WHERE d.location = 'Kochi' | Joins can repeat outer rows if the inner side has several matches — add DISTINCT |
WHERE NOT EXISTS (SELECT 1 FROM works_on w WHERE w.emp_id = e.emp_id) | FROM emp e LEFT JOIN works_on w ON w.emp_id = e.emp_id WHERE w.emp_id IS NULL | Test a column that is never NULL in matched rows (a key) |
Correlated AVG per department | Join with a derived table of averages | The derived table is computed once — often faster |
| Scalar sub-query in SELECT | LEFT JOIN + GROUP BY | Employees with no match need LEFT JOIN and COUNT(col) |
When a question needs data from the inner table in the output (dname beside ename), a join is required. When it only needs to test for the presence or absence of matching rows, EXISTS/NOT EXISTS states the intent most clearly. Try the pairs above in the SQL playground on this page and confirm they return the same rows.
Try the problem first, then reveal the working one step at a time.
Using the sample salaries 90000, 60000, 55000, 50000, 50000, 30000, 28000, 25000, 22000, 20000, find the second highest salary in two different ways, then the 4th highest distinct salary.
Evaluate SELECT ename FROM emp e1 WHERE salary > (SELECT AVG(salary) FROM emp e2 WHERE e2.dept_id = e1.dept_id); row by row and explain what happens to Jose.
Explain why SELECT dname FROM dept WHERE dept_id NOT IN (SELECT dept_id FROM emp); returns no rows on the sample data, and give two queries that return Operations.
Trace the double-NOT-EXISTS division query for Bindu (102) and for Eby (105).
Predict the output of SELECT ename FROM emp WHERE salary > (SELECT AVG(salary) FROM emp WHERE job = 'Clerk');
Rewrite salary > ALL (SELECT salary FROM emp WHERE dept_id = 20) without ALL so that it runs on SQLite, and state the result. Would your rewrite still be equivalent for department 40?
What does SELECT ename FROM emp WHERE emp_id NOT IN (SELECT manager_id FROM emp); return on the sample data? Fix it and give the corrected result.
Write two queries for the 3rd highest distinct salary and give the answer.
List the projects whose budget is above the average project budget, showing the sub-query's value.
= (sub-query) needs exactly one row; with several rows Oracle raises ORA-01427 (SQLite silently takes the first row). Use IN for sets.EXISTS (SELECT NULL …) is TRUE whenever a row exists.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.