]> begriffs open source - ai-pg/blob - full-docs/txt/plpgsql-expressions.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / plpgsql-expressions.txt
1
2 41.4. Expressions #
3
4    All expressions used in PL/pgSQL statements are processed using the
5    server's main SQL executor. For example, when you write a PL/pgSQL
6    statement like
7 IF expression THEN ...
8
9    PL/pgSQL will evaluate the expression by feeding a query like
10 SELECT expression
11
12    to the main SQL engine. While forming the SELECT command, any
13    occurrences of PL/pgSQL variable names are replaced by query
14    parameters, as discussed in detail in Section 41.11.1. This allows the
15    query plan for the SELECT to be prepared just once and then reused for
16    subsequent evaluations with different values of the variables. Thus,
17    what really happens on first use of an expression is essentially a
18    PREPARE command. For example, if we have declared two integer variables
19    x and y, and we write
20 IF x < y THEN ...
21
22    what happens behind the scenes is equivalent to
23 PREPARE statement_name(integer, integer) AS SELECT $1 < $2;
24
25    and then this prepared statement is EXECUTEd for each execution of the
26    IF statement, with the current values of the PL/pgSQL variables
27    supplied as parameter values. Normally these details are not important
28    to a PL/pgSQL user, but they are useful to know when trying to diagnose
29    a problem. More information appears in Section 41.11.2.
30
31    Since an expression is converted to a SELECT command, it can contain
32    the same clauses that an ordinary SELECT would, except that it cannot
33    include a top-level UNION, INTERSECT, or EXCEPT clause. Thus for
34    example one could test whether a table is non-empty with
35 IF count(*) > 0 FROM my_table THEN ...
36
37    since the expression between IF and THEN is parsed as though it were
38    SELECT count(*) > 0 FROM my_table. The SELECT must produce a single
39    column, and not more than one row. (If it produces no rows, the result
40    is taken as NULL.)