✏️ Explanatory Question

What is a subquery and what are its types?

👁 8 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 6: Subqueries & Set Operations

43

What is a subquery and what are its types?

Level: Intermediate — Subqueries are the foundation of complex, nested SQL logic.

A subquery (or inner/nested query) is a SELECT query placed inside another SQL statement. The inner query runs first, and its result is used by the outer query. Subqueries can appear in the SELECT, FROM, WHERE, or HAVING clause.

Key rule: A subquery must be enclosed in parentheses. When used with comparison operators like =, it must return a single value; with IN, it can return multiple values.

Types of Subqueries (by result shape)

  • Scalar subquery: Returns a single value (one row, one column).
  • Row subquery: Returns a single row with multiple columns.
  • Column subquery: Returns a single column with multiple rows (used with IN).
  • Table subquery: Returns a full table (multiple rows & columns), used in the FROM clause (a "derived table").

Types by Dependency

  • Non-correlated: The subquery runs independently of the outer query (executed once).
  • Correlated: The subquery references the outer query and runs once per outer row.

Subquery Types Summary

Type Returns Common Operator
Scalar One value =, >, <
Column One column, many rows IN, ANY, ALL
Row One row, many columns = (with row constructor)
Table Full result set FROM (derived table)

Quick Example — Each Type

-- Scalar subquery: employees earning above the average
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

-- Column subquery: employees in Kolkata departments (IN)
SELECT name FROM employees
WHERE dept_id IN (SELECT dept_id FROM departments WHERE location = 'Kolkata');

-- Table subquery (derived table) in FROM
SELECT dept_id, avg_sal
FROM (
    SELECT dept_id, AVG(salary) AS avg_sal
    FROM employees
    GROUP BY dept_id
) AS dept_avg
WHERE avg_sal > 50000;

-- Subquery in SELECT: show each employee's dept name
SELECT name,
       (SELECT dept_name FROM departments d
        WHERE d.dept_id = e.dept_id) AS department
FROM employees e;
Interviewer tip: Classify subqueries two ways — by result shape (scalar, row, column, table) and by dependency (correlated vs non-correlated). Mentioning both impresses interviewers.