From: Tom Lane <tgl@sss.pgh.pa.us>
To: logik@centrum.cz
Cc: pgsql-bugs@postgresql.org
Subject: Re: BUG #6440: Window function in WHERE evaluated after agregate
Date: Wed, 08 Feb 2012 11:52:21 -0500
Message-ID: <27361.1328719941@sss.pgh.pa.us> (raw)
In-Reply-To: <E1Rv7uy-0002pB-Vf@wrigleys.postgresql.org>
References: <E1Rv7uy-0002pB-Vf@wrigleys.postgresql.org>
logik@centrum.cz writes:
> Window function in WHERE clause - as all other functions used in where -
> should be evaluated before agregating takes place.
Hmm? WHERE clauses are necessarily evaluated before aggregating; that's
one of the main reasons why there's a difference between WHERE and
HAVING in the first place. Read the SQL standard, or any book about SQL.
> select person, sum(result) from
> results
> where
> row_number() over (partition by person, discipline order by result desc) =
> 1
> group by
> person
> Error:
> ERROR: column "results.result" must appear in the GROUP BY clause or be
> used in an aggregate function
> LINE 19: ...() over (partition by person, discipline order by result des...
The real reason this query isn't allowed can be found in SQL:2008
section 4.15.3 "Window functions":
Window functions may only appear in the <select list> of a <query
specification> or <select statement: single row>, or the <order by
clause> simply contained in a <query expression> that is a
simple table query.
I agree that the error message could be improved --- it'd be better if
it complained that you can't put a window function call there. You
would eventually get "window functions not allowed in WHERE clause",
but the other check is being made first.
As far as fixing your problem goes, maybe you should put the aggregate,
GROUP BY, and row_number() calls into a sub-select and put the WHERE in
the upper level. Or consider using LIMIT, which is going to be a lot
more efficient than this row_number() = 1 locution anyway.
regards, tom lane
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-bugs@postgresql.org
Cc: tgl@sss.pgh.pa.us, logik@centrum.cz
Subject: Re: BUG #6440: Window function in WHERE evaluated after agregate
In-Reply-To: <27361.1328719941@sss.pgh.pa.us>
References: <E1Rv7uy-0002pB-Vf@wrigleys.postgresql.org> <27361.1328719941@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox