pg.ddx.io  pgsql-docs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: PG Doc comments form <noreply@postgresql.org>
To: pgsql-docs@lists.postgresql.org
Cc: cpainterwakefield@gmail.com
Subject: clarification on chaining of set operations
Date: Mon, 04 Oct 2021 23:08:37 +0000
Message-ID: <163338891727.12510.3939775743980651160@wrigleys.postgresql.org> (raw)

The following documentation comment has been logged on the website:

Page: https://www.postgresql.org/docs/12/queries-union.html
Description:

Apologies if this has been raised previously - I searched the archives and
did not find anything.

Regarding section 7.4 of the documentation.  I was curious about the
behavior when combining different set operations in one query, e.g, 
query1 op1 query2 op2 query3;
where op1 and op2 are one of UNION, INTERSECT, EXCEPT.

The documentation suggests that this is equivalent to 
(query1 op1 query2) op2 query3;
but only states it for the case when op1 = op2 = UNION.  (Which really
doesn't matter anyway given that set union is associative.)

In fact, mixing INTERSECT and UNION does not exhibit the expected behavior
(at least in version 12 - I have not tested in later versions).  Here's my
counterexample:

CREATE TABLE test1 (x INTEGER);
CREATE TABLE test2 (x INTEGER);
CREATE TABLE test3 (x INTEGER);

INSERT INTO test1 VALUES (1), (2);
INSERT INTO test2 VALUES (2), (3);
INSERT INTO test3 VALUES (3), (4);

SELECT * FROM test1
UNION
SELECT * FROM test2
INTERSECT
SELECT * FROM test3;

(SELECT * FROM test1
UNION
SELECT * FROM test2)
INTERSECT
SELECT * FROM test3;

The observed behavior suggests that INTERSECT is applied before UNION.  I
haven't tested to figure out other interactions (e.g., with EXCEPT or the
ALL variations).


view thread (2+ messages)  latest in thread

Message-ID: <163338891727.12510.3939775743980651160@wrigleys.postgresql.org>
Permalink:  ../163338891727.12510.3939775743980651160@wrigleys.postgresql.org/
Also on:    postgresql.org/message-id/163338891727.12510.3939775743980651160@wrigleys.postgresql.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-docs@postgresql.org
  Cc: noreply@postgresql.org, pgsql-docs@lists.postgresql.org, cpainterwakefield@gmail.com
  Subject: Re: clarification on chaining of set operations
  In-Reply-To: <163338891727.12510.3939775743980651160@wrigleys.postgresql.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox