Scalar
Subqueries
Learn how to embed a query inside another query to compute single values on the fly: from averages to lookups, all within your SELECT statement.
What Is a Subquery?
A subquery is a complete SQL query nested inside another SQL statement. It is enclosed in parentheses and can appear in different clauses: SELECT, FROM, WHERE, and more.
What Makes It "Scalar"?
A scalar subquery is a subquery that returns exactly one row and one column: a single value. The word "scalar" comes from mathematics, meaning a single number rather than a vector or table.
Why Use Scalar Subqueries?
Scalar subqueries let you add context to every row: "How does this employee's salary compare to the company average?" becomes a single query instead of two.
The Core Rule
Anatomy of the Syntax
Scalar vs. Table Subqueries
| Scalar Subquery | Table Subquery | |
|---|---|---|
| Returns | 1 row, 1 column | Multiple rows/columns |
| Used in | SELECT, WHERE, HAVING | FROM, WHERE (with IN/EXISTS) |
| Common pattern | Aggregate function | Derived table, IN list |
| Error if wrong? | Yes: >1 row fails | No: returns a set |
| Example use | Compare row to average | Filter by a set of IDs |
How to Apply It
Example 1: Company Average
Show each employee's salary alongside the company-wide average salary.
Example 2: Difference From Average
Compute how much each employee's salary differs from the company average.
Example 3: Cross-Table Lookup
Show each order along with the customer name from a different table, using a correlated scalar subquery.
Correlated vs. Uncorrelated
Example 4: Using MAX
Display each product alongside the highest price in the entire catalog.
Example 5: Percentage of Total
Calculate each department's budget as a percentage of the total company budget.
Common Mistakes
Summary at a Glance
| Concept | Key Point |
|---|---|
| Scalar Subquery | Returns exactly 1 row, 1 column |
| Placement | Inside SELECT clause as a column |
| Best With | AVG, SUM, COUNT, MAX, MIN |
| Uncorrelated | Runs once, same value every row |
| Correlated | Runs per row, can reference outer columns |
| Must Have | Parentheses + alias with AS |
Question 1 of 5
A scalar subquery must return:
Question 2 of 5
Which SQL clause is this lesson focused on placing scalar subqueries into?
Question 3 of 5
What will happen if you write a scalar subquery in SELECT that returns 5 rows?
Question 4 of 5
Given the query below, what does avg_score represent?
Question 5 of 5
Which of the following is not a valid scalar subquery in SELECT?