SQL Scalar Subqueries
A scalar subquery returns one value, which makes it useful for row-by-row comparisons against a calculated benchmark.
A scalar subquery is a nested SELECT that
returns one value: one row, one column. You can use that value anywhere SQL
expects a single value, such as the right side of a comparison.
The pattern is useful when a row needs to be compared with a benchmark that also comes from the data. For example, "products whose price is above the average product price" needs the average first, then uses it as a filter.
select column_one, metric
from table_name
where metric > (
select avg(metric)
from table_name
) Keep scalar subqueries truly scalar
The inner query must return exactly one column and no more than one row. An
aggregate such as avg(price), max(order_date), or
count(*) naturally fits because it collapses many rows into one
value. Return two rows and DuckDB stops with
More than one row returned by a subquery.
Preparing for an interview? The subquery interview questions put this chapter under pressure, with model answers to compare against.
Schema · Garden Shop Table · products 9 columns · 24 rows
One row per product, with price, cost, and inventory levels.
Show every product whose price is above the
overall average product price. Return
product_name and price, most expensive first,
breaking ties by product name.
Run your query to inspect the result.
Expected answer
- Columns: product_name, price.
- Rows: 11 products priced above the overall average of about 14.36.
- The subquery returns one average price for the whole products table.
Related
Nested SELECTs, IN, EXISTS, and correlation.
Ranking, LAG/LEAD, and running totals at a glance.
Practice ranking, running totals, and top row per group.
The default RANGE frame groups tied rows; use ROWS.
Filter window results in a CTE or with QUALIFY.
The WITH clause, chained steps, and CTE vs subquery.