Re: Howto sort the result of UNION (without modifying its type)?

From: Rob Sargent <robjsargent(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Howto sort the result of UNION (without modifying its type)?
Date: 2011-04-08 22:42:52
Message-ID: 4D9F8F6C.5050702@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On 04/08/2011 03:44 PM, Clemens Eisserer wrote:
> Hi,
>
> I have a query where I UNION several select statements which return
> IDs of type INTEGER.
> This works well, if the IDs don't need to be sorted:
>> SELECT id FROM table WHERE id IN ((select id FROM table WHERE ...) UNION (SELECT id FROM table_ WHERE ....))
>
>
> However I need the result the UNIONs to be sorted, so I tried the following:
>
>> SELECT id FROM table WHERE id IN (SELECT col0 FROM ((select id FROM table WHERE ...) UNION (SELECT id FROM table_ WHERE ....)) AS col0 ORDER BY col0 OFFSET X LIMIT Y)
> FEHLER: Operator existiert nicht: integer = record
> ERROR: Operator does not exist: integer = record
> LINE 1: Select id FROM table WHERE id IN (Select col0 FROM ...
>
> Is there any way to get the results of UNIONs sorted, without
> converting it to record?
>
> Thanks, Clemens
>
> PS: I know the query looks really stupid, however the queries I UNION
> are auto-generated SQL.
> I don't have much choice here to write the query more efficient :/
>

does this work for you?

select u.id from (your unions) as u order by u.id

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Jeff Davis 2011-04-08 23:21:57 Re: Deferred foreign key constraint downsides
Previous Message momjian 2011-04-08 22:29:24 Critical fix for pg_upgrade/pg_migrator users