From 2edfe8d92f43851e3df581c24abaaba9f4de6932 Mon Sep 17 00:00:00 2001 From: Marti Raudsepp 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. + + + Implementation Notes + + When a conditional expression depends on the results of aggregate + functions in a SELECT or 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: + + +SELECT CASE WHEN min(employees)>0 + THEN average(expenses / employees) + END + FROM departments + + + 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 ] table_name [ * ] If the GROUP BY clause is specified, the output is combined into groups of rows that match on one or more - values. If the HAVING clause is present, it + values. All aggregate functions and their argument expressions + in the SELECT and HAVING are evaluated. + If the HAVING clause is present, it eliminates groups that do not satisfy the given condition. (See and below.) -- 2.1.2