Re: Clarification on the column order of UNION, INTERSECT, and EXCEPT

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: ruud(at)chorus(dot)one, PostgreSQL Documentation <pgsql-docs(at)lists(dot)postgresql(dot)org>
Subject: Re: Clarification on the column order of UNION, INTERSECT, and EXCEPT
Date: 2025-07-25 02:55:06
Message-ID: CAKFQuwY0eKOHoD=CnfaJgRwvM7XpC+FM0y57YEB+C+SVpJKaoA@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-docs

On Thu, Jul 24, 2025, 09:22 PG Doc comments form <noreply(at)postgresql(dot)org>
wrote:

> The following documentation comment has been logged on the website:
>
> Page: https://www.postgresql.org/docs/17/queries-union.html
> Description:
>
> When combining queries with UNION, INTERSECT, or EXCEPT, columns are
> matched
> in the order in which they occur, and not by column name. This can be
> unexpected, and I think it would be helpful to call it out explicitly in
> the
> documentation.

The docs never imply that matching by name is a thing in SQL generally.
People make assumptions all the time and we generally don't try and write
to anticipate and disabuse people of random assumptions. We instead
document how things work. We don't document here that all column names in
both queries must be identical which is what your assumption would require.

The existing wording strongly implies that corresponding matches are done
by index. Then concretely an example on that page unions columns, A and X,
this clearly showing that names are immaterial and, like the requirements
state, data type matching columns at each position are paired.

I could maybe see adding "position" somewhere but calling it out with a
warning seems unnecessary. Even if one gets confused it is immediately
obvious when checking the result that there is an issue.

David J.

In response to

Browse pgsql-docs by date

  From Date Subject
Next Message Alexander Korotkov 2025-07-28 10:20:06 Re: Initcap works differently with different locale providers
Previous Message Fujii Masao 2025-07-24 02:56:36 Re: Minor Improvements to pg_buffercache documentation