SQL Subqueries
A subquery is a query inside another query. Itβs used to fetch intermediate results for comparison, filtering, or transformation.
Types of subqueries:
- Scalar Subquery β returns a single value
- Row Subquery β returns a single row
- Table Subquery β returns a full result set (multiple rows & columns)
πΉ Scalar Subquery β One Value
Used where a single value is expected (e.g., in SELECT, WHERE, SET).
SELECT employee_name
FROM employees
WHERE salary > (
SELECT AVG(salary) FROM employees
);
β Filters employees earning above average salary.
πΉ Row Subquery β One Row, Multiple Columns
Used to compare a row with another row.
SELECT employee_id, first_name
FROM employees
WHERE (department_id, job_id) = (
SELECT department_id, job_id
FROM employees
WHERE employee_id = 101
);
β Returns employees who share both department and job with employee 101.
πΉ Table Subquery β Used in FROM
Returns a full table-like result that can be queried.
SELECT dept_name, emp_count
FROM (
SELECT department_id, COUNT(*) AS emp_count
FROM employees
GROUP BY department_id
) AS dept_summary
JOIN departments d ON d.department_id = dept_summary.department_id;
β You can treat the subquery as a temporary table.
πΉ Subquery in SELECT
SELECT
employee_name,
(SELECT department_name FROM departments d WHERE d.department_id = e.department_id) AS dept_name
FROM employees e;
π§ Quick Recap
Type | Description | Returns |
---|---|---|
Scalar | One value | Single value |
Row | One full row | Multiple columns |
Table | Treated like a table in the main query | Rows + columns |
Use in | SELECT, FROM, WHERE, HAVING | Anywhere in query |
π‘ Subqueries add power and flexibility β ideal for comparisons and reusable logic.