Re: UNION with ORDER BY -allowed? - Mailing list pgsql-general

From John Sidney-Woollett
Subject Re: UNION with ORDER BY -allowed?
Date
Msg-id 41AF302A.7090802@wardbrook.com
Whole thread Raw
In response to UNION with ORDER BY -allowed?  (Chris Green <chris@areti.co.uk>)
Responses Re: UNION with ORDER BY -allowed?  (<terry@ashtonwoodshomes.com>)
List pgsql-general
wrap the whole statement in another select

select col1, col2, col5, col6 from (
      SELECT
          col1, col2, col5, col6
      FROM
          table
      WHERE
          col2 = 'X'
      UNION
      SELECT
          col3, col4, col5, col6
      FROM
          table
      WHERE
          col4 = 'X'
) as t
order by coalesce(col1, col3);

John Sidney-Woollett

Chris Green wrote:

> It's not quite clear (to me at least) whether I can have a UNION and
> an ORDER BY in a SELECT statement.
>
> What I want to do is:-
>
>     SELECT
>         col1, col2, col5, col6
>     FROM
>         table
>     WHERE
>         col2 = 'X'
>     UNION
>     SELECT
>         col3, col4, col5, col6
>     FROM
>         table
>     WHERE
>         col4 = 'X'
>     ORDER BY
>         coalesce(col1, col3)
>
> Is this valid syntax allowed by postgresql?  (I'm not at the system
> where postgresql is installed at the moment so I can't just try it)
>
> col1 and col3 are both DATE columns.  col2 and col4 are both
> varchar(1).
>
> I want the ORDER BY to order the result of the UNION.
>

pgsql-general by date:

Previous
From: Chris Green
Date:
Subject: UNION with ORDER BY -allowed?
Next
From:
Date:
Subject: Re: UNION with ORDER BY -allowed?