What is a scalar subquery, and where can it appear?
EasyA subquery that returns exactly one row and one column, usable anywhere a single value is allowed: the SELECT list, WHERE comparisons, even ORDER BY.
SELECT name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c;
Two follow-ups. If the subquery returns more than one row, PostgreSQL, SQL Server, MySQL and Oracle raise a runtime error, while SQLite silently uses the first row; if it returns no rows, the value is NULL, so a COUNT subquery is safe but a SUM one may need COALESCE. And a correlated scalar subquery is logically evaluated once per outer row: some optimizers turn it into a join, PostgreSQL generally does not, so on large tables a LEFT JOIN to a grouped subquery is often faster.