Passing SELECT output into variables

    Available in

    PSQL

    A “plain” SELECT statement can only be used in PSQL if it returns at most one row, i.e., if it is a singleton select. For multi-row selects, PSQL provides the loop construct, discussed later in the PSQL chapter. PSQL also supports the statement, which binds a named cursor to a SELECT statement. The cursor can then be used to walk the result set.

    Syntax

    In PSQL the INTO clause is placed at the very end of the SELECT statement.

    Examples

    Selecting some aggregated values and passing them into previously declared variables min_amt, and max_amt:

    The CAST serves to make the average a real number; otherwise, since amount is presumably an integer field, SQL rules would truncate it to the nearest lower integer.

    A PSQL trigger that retrieves two values as a BLOB field (using the LIST() function) and assigns it a third field: