From 2edfe8d92f43851e3df581c24abaaba9f4de6932 Mon Sep 17 00:00:00 2001
From: Marti Raudsepp <marti@juffo.org>
Date: Tue, 14 Oct 2014 01:33:41 +0300
Subject: [PATCH] doc: Clarify evaluation order of aggregates wrt conditionals

---
 doc/src/sgml/func.sgml       | 19 +++++++++++++++++++
 doc/src/sgml/ref/select.sgml |  4 +++-
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml
index 3a7cfa9..76770fc 100644
--- a/doc/src/sgml/func.sgml
+++ b/doc/src/sgml/func.sgml
@@ -11251,6 +11251,25 @@ SELECT NULLIF(value, '(none)') ...
     make them return NULL if any argument is NULL, rather than only when
     all are NULL.
    </para>
+
+  <sect2 id="implementation">
+   <title>Implementation Notes</title>
+   <para>
+    When a conditional expression depends on the results of aggregate
+    functions in a <command>SELECT</> or <literal>HAVING</> clause, then all
+    the aggregate functions are always evaluated prior to determining which
+    branch the conditional should take.  For example, the following query can
+    cause a "division by zero" error despite only using division in a branch
+    that requires positive values:
+
+<programlisting>
+SELECT CASE WHEN min(employees)>0
+            THEN average(expenses / employees)
+       END
+    FROM departments
+</programlisting>
+   </para>
+
   </sect2>
  </sect1>
 
diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml
index 473939a..97b3503 100644
--- a/doc/src/sgml/ref/select.sgml
+++ b/doc/src/sgml/ref/select.sgml
@@ -111,7 +111,9 @@ TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
      <para>
       If the <literal>GROUP BY</literal> clause is specified, the
       output is combined into groups of rows that match on one or more
-      values.  If the <literal>HAVING</literal> clause is present, it
+      values.  All aggregate functions and their argument expressions
+      in the <command>SELECT</> and <literal>HAVING</> are evaluated.
+      If the <literal>HAVING</literal> clause is present, it
       eliminates groups that do not satisfy the given condition.  (See
       <xref linkend="sql-groupby" endterm="sql-groupby-title"> and
       <xref linkend="sql-having" endterm="sql-having-title"> below.)
-- 
2.1.2

