Re: UNION?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Forest Felling <res08i7v(at)verizon(dot)net>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: UNION?
Date: 2003-01-20 15:48:22
Message-ID: 3317.1043077702@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Forest Felling <res08i7v(at)verizon(dot)net> writes:
> mydb=# select count(city) as qty, code as code
> from test_year
> where length(code) = 1
> group by code
> order by code
> union all
> select count(city) as qty, 'All' as code
> from test_year
> where length(code) = 1
> ERROR: parser: parse error at or near "all"

If you want to use ORDER BY in one of the elements of a UNION (which is
not legal per standard SQL), you need to parenthesize:

(select count(city) as qty, code as code
from test_year
where length(code) = 1
group by code
order by code)
union all
(select count(city) as qty, 'All' as code
from test_year
where length(code) = 1)

The reason for this can be seen by considering this variant query:

(select count(city) as qty, 'All' as code
from test_year
where length(code) = 1)
union all
(select count(city) as qty, code as code
from test_year
where length(code) = 1
group by code
order by code)

Without the parens, it would be unclear whether you mean the ORDER BY
to apply to the second sub-SELECT, or to the result of the whole UNION.
(SQL spec would require it to be interpreted as applying to the whole
UNION result, I believe.)

regards, tom lane

In response to

  • UNION? at 2003-01-20 13:52:09 from Forest Felling

Browse pgsql-novice by date

  From Date Subject
Next Message Chris Boget 2003-01-20 15:53:38 Re: OID
Previous Message Manfred Koizar 2003-01-20 15:47:35 Re: OID