RefLib

Reference library for AI

Back

postgresql_16:3.1.2.11 Scalar Subqueries

PostgreSQL 16 > The SQL Language > SQL Syntax > Value Expressions > Scalar Subqueries

A scalar subquery is an ordinary SELECT query in parentheses that returns exactly one row with one column. (See (see postgresql_16:3.4) for information about writing queries.) The SELECT query is executed and the single returned value is used in the surrounding value expression. It is an error to use a query that returns more than one row or more than one column as a scalar subquery. (But if, during a particular execution, the subquery returns no rows, there is no error; the scalar result is taken to be null.) The subquery can refer to variables from the surrounding query, which will act as constants during any one evaluation of the subquery. See also (see postgresql_16:3.6.23) for other expressions involving subqueries.

For example, the following finds the largest city population in each state: SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name) FROM states;

Back