Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id 5F868175B7F1 for ; Wed, 28 Mar 2012 11:13:25 -0300 (ADT) Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1SCtci-00086X-43 for pgsql-performance@postgresql.org; Wed, 28 Mar 2012 14:13:24 +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 q2SED1Zk022626; Wed, 28 Mar 2012 10:13:02 -0400 (EDT) To: Francois Deliege cc: pgsql-performance@postgresql.org Subject: Re: Distinct + Limit In-reply-to: <16737833.463.1332881676120.JavaMail.geo-discussion-forums@pbcpw7> References: <5833589.541.1332880671745.JavaMail.geo-discussion-forums@pbbnv8> <16737833.463.1332881676120.JavaMail.geo-discussion-forums@pbcpw7> Comments: In-reply-to Francois Deliege message dated "Tue, 27 Mar 2012 13:54:36 -0700" Date: Wed, 28 Mar 2012 10:13:01 -0400 Message-ID: <22625.1332943981@sss.pgh.pa.us> From: Tom Lane X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201203/174 X-Sequence-Number: 46624 Francois Deliege writes: > I have the following table with millions of rows: > CREATE TABLE table1 > ( > col1 text, > col2 text, > col3 text, > col4 text, > col5 text, > col6 text > ) > select col1 from table1 group by col1 limit 1; > select distinct on (col1) col1 from table1 limit 1; > select col1 from table1 group by col1 limit 2; > select distinct on (col1) col1 from table1 limit 2; > Performing any of these following queries results in a full sequential scan, followed by a hash aggregate, and then the limit. Well, if you had an index on the column, you would get a significantly better plan ... > Similarly, the following query results in a sequential scan: > select * from table1 where col1 <> col1; > This query is generated by the Sequel library abstraction layer in Ruby when filtering record based on a empty array of values. We fixed this by handling that case on the client side, but originally thought the server would have rewritten it and sent a empty result set. It does not, and never will, because that would be an incorrect optimization. "col1 <> col1" isn't constant false, it's more like "col1 is not null". I'd suggest "WHERE FALSE", or "WHERE 1 <> 1" if you must, to generate a provably false constraint. regards, tom lane