Lab 07 — Subqueries
Queries inside queries. Use subqueries to filter by computed values, create derived tables, and answer complex HR questions.
📖 Concept Recap: Subqueries
- A subquery is a SELECT statement nested inside another query, enclosed in parentheses.
- Subquery in WHERE: filter rows by a computed value —
WHERE salary > (SELECT AVG(salary) FROM employees) - Subquery in FROM: treat the result as a temporary table (derived table) —
FROM (SELECT ...) AS sub - Correlated subquery: inner query references the outer row — executes once per outer row.
- Use IN with subqueries that return a list:
WHERE dept_id IN (SELECT id FROM departments WHERE ...) - Use NOT IN / NOT EXISTS to find rows with no matching counterpart.
👀 Worked Example (read-only)
Find employees earning above the company-wide average.
-- Employees earning above the overall average salary SELECT name, salary, dept_id FROM employees WHERE salary > (SELECT AVG(salary) FROM employees) ORDER BY salary DESC;
Exercise 1 — Employees in the Highest-Budget Department
Find all employees who work in the department with the largest budget. Fill in the aggregate function name to complete the nested subquery.
WHERE budget = (SELECT MAX(budget) FROM departments)Exercise 2 — Correlated Subquery: Above Their Own Department Average
Find employees who earn more than the average salary of their own specific department. The subquery must reference the outer row's dept_id.
WHERE e.salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id)Exercise 3 — Departments Where ALL Employees Earn Above $80,000
Use NOT IN to find departments that do not appear in the set of department IDs where any employee earns $80,000 or less. Show department stats.
WHERE d.id NOT IN (SELECT DISTINCT dept_id FROM employees WHERE salary <= 80000)Mini Project — HR Subquery Analysis
Answer these four HR questions using subqueries:
- Which employees are assigned to the highest-budget project?
- Which departments have an above-average budget (above the mean of all departments)?
- Which employees are assigned to more projects than the average number of assignments per employee (use a derived table subquery in FROM)?
- The top earner in each department (correlated subquery in WHERE).
🏁 Lab 07 Complete!
You can now write scalar subqueries in WHERE, derived table subqueries in FROM, and correlated subqueries that reference the outer query.
Next: manipulating text and dates with SQL functions.
Continue to Lab 08 — String & Date Functions →