Sub topic 2
Scalar subqueries: one value from a query
This chapter assumes you know SELECT, WHERE, ORDER BY, aggregate functions such as AVG, and basic joins. You should also understand that NULL means an unknown or missing value.
A subquery is a query nested inside another SQL statement. A scalar subquery is a subquery that produces one value: one column from zero or one row. The outer query can use that value wherever a single value is allowed.
Comparing with an aggregate result
Suppose employees contains name and salary. To find employees whose salary is above the company average, first calculate the average, then compare each salary with it:
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);The inner query calculates one average salary. The outer query evaluates the condition for each employee.
The parentheses are required because the subquery is being used as an expression. The database conceptually evaluates the query like this:
company average = SELECT AVG(salary) FROM employees
keep each employee where salary > company averageThe aggregate function AVG normally produces one row, even when the table has no rows. In that case, its result is NULL, so the comparison is not true for any employee.
The scalar result contract
A scalar subquery must return no more than one row and exactly one column. If it returns two or more rows, the database usually reports an error because it cannot compare one salary with multiple values.
For example, this is unsafe unless id is unique:
SELECT name
FROM employees
WHERE salary = (
SELECT salary
FROM employees
WHERE department_id = 10
);Department 10 may contain several employees, so the inner query may return several salaries. Use an aggregate when the question asks for one summary value:
SELECT name
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
WHERE department_id = 10
);This query finds employees whose salary equals the highest salary in department 10.
A subquery that returns zero rows produces NULL in most SQL systems. A comparison such as salary > NULL is unknown, not true. If you need a fallback value, use a database-supported function such as COALESCE:
SELECT name, salary
FROM employees
WHERE salary > COALESCE(
(SELECT AVG(salary) FROM employees),
0
);Use a fallback only when it matches the meaning of missing data. Replacing an unknown average with zero may be appropriate for a particular report, but it can also hide an empty or invalid data set.
Reading the evaluation flow
A scalar subquery often makes a layered question easier to read: “return rows whose value is above this calculated value.” The database may optimize the query internally, so the written nesting does not necessarily mean the inner query runs once for every outer row.
Choosing a scalar subquery
Use a scalar subquery when the inner query naturally answers a single-value question:
- What is the company-wide average?
- What is the latest order date?
- What is the maximum salary in a department?
- What is the tax rate stored in a settings table?
If the inner query should return several values, a scalar subquery is the wrong form. Use a multi-row operator such as IN, or rewrite the question as a join.
Exercise
What usually happens if a scalar subquery returns two rows?
Show answer
The database raises an error because the outer expression expects one value, not multiple values.