Doc: improve description of UNION/INTERSECT/EXCEPT syntax.
authorTom Lane
Tue, 5 Oct 2021 14:24:14 +0000 (10:24 -0400)
committerTom Lane
Tue, 5 Oct 2021 14:24:14 +0000 (10:24 -0400)
queries.sgml failed to mention the rather important point that
INTERSECT binds more tightly than UNION or EXCEPT.  I thought
it could also use more discussion of the role of parentheses
in these constructs.

Per gripe from Christopher Painter-Wakefield.

Discussion: https://postgr.es/m/163338891727.12510.3939775743980651160@wrigleys.postgresql.org

doc/src/sgml/queries.sgml

index 834b83b50982f9572d09ce7c90b6e7af0c4578b0..516fbcbf375bbab7f5a74f3fe5f1d07404a01c1b 100644 (file)
@@ -1707,17 +1707,9 @@ SELECT DISTINCT ON (expression 
 query1 INTERSECT ALL query2
 query1 EXCEPT ALL query2
 
-   query1 and
+   where query1 and
    query2 are queries that can use any of
-   the features discussed up to this point.  Set operations can also
-   be nested and chained, for example
-
-query1 UNION query2 UNION query3
-
-   which is executed as:
-
-(query1 UNION query2) UNION query3
-
+   the features discussed up to this point.
   
 
   
@@ -1751,6 +1743,47 @@ SELECT DISTINCT ON (expression 
    the corresponding columns have compatible data types, as
    described in .
   
+
+  
+   Set operations can be combined, for example
+
+query1 UNION query2 EXCEPT query3
+
+   which is equivalent to
+
+(query1 UNION query2) EXCEPT query3
+
+   As shown here, you can use parentheses to control the order of
+   evaluation.  Without parentheses, UNION
+   and EXCEPT associate left-to-right,
+   but INTERSECT binds more tightly than those two
+   operators.  Thus
+
+query1 UNION query2 INTERSECT query3
+
+   means
+
+query1 UNION (query2 INTERSECT query3)
+
+   You can also surround an individual query
+   with parentheses.  This is important if
+   the query needs to use any of the clauses
+   discussed in following sections, such as LIMIT.
+   Without parentheses, you'll get a syntax error, or else the clause will
+   be understood as applying to the output of the set operation rather
+   than one of its inputs.  For example,
+
+SELECT a FROM b UNION SELECT x FROM y LIMIT 10
+
+   is accepted, but it means
+
+(SELECT a FROM b UNION SELECT x FROM y) LIMIT 10
+
+   not
+
+SELECT a FROM b UNION (SELECT x FROM y LIMIT 10)
+
+