Re: ORDER BY in UNION query

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: Antony Paul <antonypaul24(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: ORDER BY in UNION query
Date: 2005-01-10 13:39:50
Message-ID: 11160.1105364390@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Richard Huxton <dev(at)archonet(dot)com> writes:
> Antony Paul wrote:
>> I need to use ORDER BY clause in a UNION query and the Order BY
>> columns are not included in the SELECT statement. I tried like this
>>
>> (select .... from a) UNION (select ..... from b) order by a.ename;
>>
>> It says that
>> ERROR: Attribute "ename" not found

> The "order by" is applying to the results of the union, not one of the
> sub-selects. If you want to sort by a value, you'll need to include it
> in the results list.

You could suppress the order-by fields after the fact:

SELECT x,y,z FROM
( (SELECT x,y,z,q FROM a)
UNION
(SELECT x,y,z,q FROM b)
ORDER BY q
) ss;

Also, always ask yourself if you really need UNION or if UNION ALL
is sufficient. Removing duplicates from a large UNION is *expensive*,
and all too often a waste of time.

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2005-01-10 13:57:53 Re: could not open relation No such file or directory after alter table
Previous Message Tom Lane 2005-01-10 13:30:26 Re: Transaction size