Scalar subqueries: use one result as a value
Overview
A scalar subquery is a parenthesized query used where one value is expected. Use it to compare a price with the overall average or calculate a single summary alongside other columns.
First example
SELECT id, name FROM productsWHERE price_cents > (SELECT AVG(price_cents) FROM products)ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 3, "Bag" ]]How it works
The average price is 750 cents; only Bag costs more. The inner AVG query returns one row and one column, even when its input is empty (then the value is NULL). A scalar subquery with no rows also yields NULL. PostgreSQL rejects multiple result rows; SQLite uses the first row, so never rely on accidental row selection. Here the average is independent of the outer query. A scalar subquery may appear in SELECT, WHERE or HAVING where its type is appropriate. The second example counts orders once as a logical independent result; this is not a promise about physical execution.
Practical example
SELECT id, (SELECT COUNT(*) FROM orders) AS total_ordersFROM customers ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 3 ], [ 2, 3 ], [ 3, 3 ]]Practice and mistakes
Practice: find products cheaper than the average (IDs 1, 2, 4). Predict what happens if the average is computed over an empty filtered table: no price passes the comparison. Do not confuse an aggregate over no rows with a nonaggregate query returning no rows.