ADVERTISEMENT

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

TypeDescriptionReturns
ScalarOne valueSingle value
RowOne full rowMultiple columns
TableTreated like a table in the main queryRows + columns
Use inSELECT, FROM, WHERE, HAVINGAnywhere in query

πŸ’‘ Subqueries add power and flexibility β€” ideal for comparisons and reusable logic.

ADVERTISEMENT