Skip to content
Advertisement

Categorizing a sub-expression within an expression

Let’s say I have the following select_expr:

SELECT
    name,
    4 + (
       (SELECT SUM(revenue) FROM tbl WHERE name=tbl.name)
       / (SELECT COUNT(revenue) FROM tbl WHERE name=tbl.name)
    )
FROM tbl

Ignoring the fact that this query doesn’t make sense, I’m curious how the second select_expr would be categorized:

4  + (SELECT ...) / (SELECT ...)

I suppose all three items can be called ‘operands’ and the second two can be called ‘sub-selects’, but is there a better way to categorize that the “subselect” is only a component of the final select expression? Sorry if this is pedantic, but I’m looking for a clear way to categorize ‘terms’ within a complex expression.

Advertisement

Answer

4  + (SELECT ...) / (SELECT ...)

You have an arithmetic operation that involves three operands. The first operand is a constant, and the two other are scalar subqueries.

The term subquery indicates that this is an intermediate result in the whole query. scalar means that the subquery returns just one row, with one column (or, possibly, no row at all – but that’s not the case here). The scalar part is the most important notion: if one of the subqueries returns more than one row (or more than one column), then it cannot be used as an operand in the arithmetic operation, and the query errors.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement