Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1ekaKJ-0005W2-GF for pgsql-docs@arkaria.postgresql.org; Sat, 10 Feb 2018 18:56:43 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1ekaKI-0001Rj-6H for pgsql-docs@arkaria.postgresql.org; Sat, 10 Feb 2018 18:56:42 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1ekaKI-0001Ra-13 for pgsql-docs@lists.postgresql.org; Sat, 10 Feb 2018 18:56:42 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1ekaKG-0002to-85 for pgsql-docs@lists.postgresql.org; Sat, 10 Feb 2018 18:56:41 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id w1AIubK7005184; Sat, 10 Feb 2018 13:56:37 -0500 From: Tom Lane To: andrew@grillet.co.uk cc: pgsql-docs@lists.postgresql.org Subject: Re: Functions in sort order - undocumented restriction In-reply-to: <151826283029.1443.7699948679319699778@wrigleys.postgresql.org> References: <151826283029.1443.7699948679319699778@wrigleys.postgresql.org> Comments: In-reply-to =?utf-8?q?PG_Doc_comments_form?= message dated "Sat, 10 Feb 2018 11:40:30 +0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <5182.1518288997.1@sss.pgh.pa.us> Date: Sat, 10 Feb 2018 13:56:37 -0500 Message-ID: <5183.1518288997@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk =?utf-8?q?PG_Doc_comments_form?= writes: > This does not work: > select distinct (o.bid), organisation, posttown, replace(case when postcode > ='' then null else trim(postcode) end, ' ', '') as pc, phone, o.active, > website, email, (select count(*) from notes as n where n.bid = o.bid) as nn > from organisations as o right join notes as n on o.bid = n.bid where true > order by replace(case when phone ='' then null else trim(phone) end, ' ', > '') nulls last ; > ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list What do you find unclear about this error message? The reason seems clear enough to me: if the ordering expression isn't one of the values that are being de-duplicated on, then there isn't a unique value to associate with each surviving row for sorting purposes. regards, tom lane