MODULE 5 OF 8: SUBQUERIES AND CTES • LESSON 1 OF 5~20 min read

Scalar and Multi-Row Subqueries

A subquery is a SELECT statement nested inside another SQL statement. It can return one value, a list of values, or a table-shaped result. Choosing the right form depends on what the outer query needs: a scalar value for comparison, a set for membership, or a derived table for a later step.

•

A subquery is a SELECT statement nested inside another SQL statement. It can return one value, a list of values, or a table-shaped result. Choosing the right form depends on what the outer query needs: a scalar value for comparison, a set for membership, or a derived table for a later step.

Key Takeaways at a Glance:

  • •A Scalar Subquery returns exactly 1 value (1 row, 1 column) and can be used anywhere an expression is expected (SELECT, WHERE).
  • •A Multi-Row Subquery returns a single column of multiple rows, used with IN, ANY, or ALL.
  • •A Derived Table is a subquery in the FROM clause and MUST be given an alias in ANSI SQL.
  • •If a scalar subquery returns more than 1 row at runtime, the query aborts with a fatal 'Subquery returns more than 1 row' error.

In Simple Words (The Mental Model)

A subquery is just a query inside another query. The database runs the inner query first to get an answer (like finding the average salary), and then plugs that answer into the outer query (like finding all employees who earn more than that average).

Real-World Analogy

Think of asking your friend: 'Go check the thermometer outside and tell me the temperature; then I will decide whether to wear a jacket'. The friend checking the thermometer is the inner subquery; you deciding whether to put on a jacket is the outer query.

Foundational Principles

Core Concept Breakdown

Essential database invariants, relational theory, and execution behavior.

1What a subquery returns

A scalar subquery returns one value: one row and one column. A multi-row subquery returns several values, often used with IN or a comparison operator such as > ANY where supported. A table subquery returns rows and columns for use in FROM. The operator around the subquery must match its result shape.

Free Preview Limit Reached (2/2 Lessons Used)

Sign In to Unlock Full Lesson Content

Visitors are limited to 2 free preview lessons. Create a free StudyVex account to unlock all 38 comprehensive theory chapters, runnable query walkthroughs, visual input & result tables, and interactive placement quizzes.