Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id 0FC321A3E38B for ; Wed, 8 Feb 2012 12:52:39 -0400 (AST) Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1RvAl3-0008Ac-1C for pgsql-bugs@postgresql.org; Wed, 08 Feb 2012 16:52:38 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id q18GqLDf027362; Wed, 8 Feb 2012 11:52:21 -0500 (EST) To: logik@centrum.cz cc: pgsql-bugs@postgresql.org Subject: Re: BUG #6440: Window function in WHERE evaluated after agregate In-reply-to: References: Comments: In-reply-to logik@centrum.cz message dated "Wed, 08 Feb 2012 13:50:40 +0000" Date: Wed, 08 Feb 2012 11:52:21 -0500 Message-ID: <27361.1328719941@sss.pgh.pa.us> From: Tom Lane X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201202/78 X-Sequence-Number: 32421 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 , or the simply contained in a 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