Learn Without Walls
← Back to SQL Labs
← Previous Lab Lab 7 of 10 — Subqueries Next Lab →

Lab 07 — Subqueries

Queries inside queries. Use subqueries to filter by computed values, create derived tables, and answer complex HR questions.

⏳ Loading SQL engine...
📋 AVAILABLE TABLES: departments, employees, projects, assignmentsdepartments(id, name, budget, location) employees(id, name, dept_id, salary, years, manager_id, hire_date) projects(id, name, dept_id, budget, status, start_date) assignments(employee_id, project_id, hours_per_week, role) Key relationships: employees.dept_id --> departments.id projects.dept_id --> departments.id assignments.employee_id --> employees.id assignments.project_id --> projects.id

📖 Concept Recap: Subqueries

👀 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;
✏ Guided

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.

💡 Hint: The inner query finds the department with the highest budget: WHERE budget = (SELECT MAX(budget) FROM departments)
💪 Independent

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.

💡 Hint: WHERE e.salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id)
🔥 Challenge

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.

💡 Hint: WHERE d.id NOT IN (SELECT DISTINCT dept_id FROM employees WHERE salary <= 80000)
🏆 Mini Project

Mini Project — HR Subquery Analysis

Answer these four HR questions using subqueries:

  1. Which employees are assigned to the highest-budget project?
  2. Which departments have an above-average budget (above the mean of all departments)?
  3. Which employees are assigned to more projects than the average number of assignments per employee (use a derived table subquery in FROM)?
  4. 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 →