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

From: Radosław Smogura <mail(at)smogura(dot)eu>
To: pgsql-general(at)postgresql(dot)org
Cc: Clemens Eisserer <linuxhippy(at)gmail(dot)com>
Subject: Re: Howto sort the result of UNION (without modifying its type)?
Date: 2011-04-16 23:35:29
Message-ID: 201104170135.29963.mail@smogura.eu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Clemens Eisserer <linuxhippy(at)gmail(dot)com> Friday 08 April 2011 23:44:21
> 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 :/

May you try construct like this:
SELECT i FROM (/* Your query example: */ SELECT i from v1 union select i from
v2) as alias order by i;
?

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2011-04-17 00:17:45 Re: New feature: selectivity - new attribute in function
Previous Message Edison So 2011-04-16 23:24:38 Re: New feature: selectivity - new attribute in function