Re: Column "..." does not exist (view + union)

From: Brent Dombrowski <brent(dot)dombrowski(at)gmail(dot)com>
To: Stefan Weiss <krewecherl(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Column "..." does not exist (view + union)
Date: 2011-12-18 02:58:18
Message-ID: 7E407B4A-8F66-45CD-804D-E97A56C808DA@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Dec 17, 2011, at 2:21 PM, Stefan Weiss wrote:

> I know, but the problem only occurs when I want to sort by a column
> which hasn't been selected, and thus cannot be referred to by its index.
> For normal (non-union) queries, this is possible:
>
> SELECT relname
> FROM pg_class
> WHERE relhasindex
> ORDER BY relpages;
>
> In this trivial case, PostgreSQL knows where to look for "relpages".
> Not so in a union:
>
> SELECT relname
> FROM pg_class
> WHERE relhasindex
> UNION
> SELECT relname
> FROM pg_class
> WHERE relhasoids
> ORDER BY relpages;
>
> (ERROR: column "relpages" does not exist)
>
> I understand the error now (I think), and I know how to avoid it.

The real problem here is the order of operations. This is what Postgres did:

SELECT * FROM (
SELECT relname
FROM pg_class
WHERE relhasindex
UNION
SELECT relname
FROM pg_class
WHERE relhasoids
) as foo
ORDER BY relpages;

It applied the union before the order by. After the union, the relpages column was projected away. Thus relpages does not exist for the order by. The postgres manual states that this is what will happen.

The UNION clause has this general form:

select_statement UNION [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Gabriel Filipiak 2011-12-19 08:16:33 Problem with tables and columns names
Previous Message Adrian Klaver 2011-12-17 23:38:43 Re: Column "..." does not exist (view + union)