11<!--
2- $Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.61 2002/06/01 20:56 :55petere Exp $
2+ $Header: /cvsroot/pgsql/doc/src/sgml/syntax.sgml,v 1.62 2002/06/15 21:28 :55tgl Exp $
33-->
44
55<chapter id="sql-syntax">
@@ -1435,14 +1435,13 @@ FROM states;
14351435
14361436 <para>
14371437 The order of evaluation of subexpressions is not defined. In
1438- particular, subexpressions are not necessarily evaluated
1439- left-to-right, right-to-left, or according to the lexical
1440- precedence rules.
1438+ particular, the inputs of an operator or function are not necessarily
1439+ evaluated left-to-right or in any other fixed order.
14411440 </para>
14421441
14431442 <para>
14441443 Furthermore, if the result of an expression can be determined by
1445- evaluating only some parts of it, thensome subexpressions
1444+ evaluating only some parts of it, thenother subexpressions
14461445 might not be evaluated at all. For instance, if one wrote
14471446<programlisting>
14481447SELECT true OR somefunc();
@@ -1459,7 +1458,27 @@ SELECT somefunc() OR true;
14591458
14601459 <para>
14611460 As a consequence, it is unwise to use functions with side effects
1462- as part of complex expressions.
1461+ as part of complex expressions. It is particularly dangerous to
1462+ rely on side effects or evaluation order in WHERE and HAVING clauses,
1463+ since those clauses are extensively reprocessed as part of
1464+ developing an execution plan. Boolean
1465+ expressions (AND/OR/NOT combinations) in those clauses may be reorganized
1466+ in any manner allowed by the laws of Boolean algebra.
1467+ </para>
1468+
1469+ <para>
1470+ When it is essential to force evaluation order, a CASE construct may
1471+ be used. For example, this is an untrustworthy way of trying to
1472+ avoid division by zero in a WHERE clause:
1473+ <programlisting>
1474+ SELECT ... WHERE x <> 0 AND y/x > 1.5;
1475+ </programlisting>
1476+ but this is safe:
1477+ <programlisting>
1478+ SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
1479+ </programlisting>
1480+ A CASE construct used in this fashion will defeat optimization attempts,
1481+ so it should only be done when necessary.
14631482 </para>
14641483 </sect2>
14651484 </sect1>