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 relhasindexUNION SELECT relname FROM pg_class
WHERErelhasoids) 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
notexist 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
LIMITcan be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be
takento apply to the result of the UNION, not to its right-hand input expression.)