Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id DB5429FB5E2 for ; Thu, 2 Aug 2007 19:37:55 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 25626-05 for ; Thu, 2 Aug 2007 19:37:43 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from oxford.xeocode.com (unknown [87.127.95.194]) by postgresql.org (Postfix) with ESMTP id 4FBB89FB4C2 for ; Thu, 2 Aug 2007 19:37:47 -0300 (ADT) Received: from localhost ([127.0.0.1] helo=oxford.xeocode.com) by oxford.xeocode.com with esmtp (Exim 4.67) (envelope-from ) id 1IGjIe-0000zM-Fs; Thu, 02 Aug 2007 23:37:44 +0100 From: Gregory Stark To: "Ron Mayer" Cc: Subject: Re: Why are distinct and group by choosing different plans? In-Reply-To: (Ron Mayer's message of "Thu, 02 Aug 2007 14:32:14 -0700") Organization: EnterpriseDB References: X-Draft-From: ("nnimap+mail01.enterprisedb.com:INBOX.performance" 1842) Date: Thu, 02 Aug 2007 23:37:43 +0100 Message-ID: <87r6mlef60.fsf@oxford.xeocode.com> User-Agent: Gnus/5.110006 (No Gnus v0.6) Emacs/21.4 (gnu/linux) MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/14 X-Sequence-Number: 26144 "Ron Mayer" writes: > I notice that I get different plans when I run the > following two queries that I thought would be > identical. > > select distinct test_col from mytable; > select test_col from mytable group by test_col; > > Any reason why it favors one in one case but not the other? I think "distinct" just doesn't know about hash aggregates yet. That's partly an oversight and partly of a "feature" in that it gives a convenient way to write a query which avoids them. I think it's also partly that "distinct" is trickier to fix because it's the same codepath as "distinct on" which is decidedly more complex than a simple "distinct". > d=# explain analyze select distinct test_col from mytable; > QUERY PLAN > ------------------------------------------------------------------------------------------------------------------------------------------------------------ > Unique (cost=0.00..14927.69 rows=27731 width=4) (actual time=0.144..915.214 rows=208701 loops=1) > -> Index Scan using "mytable(test_col)" on mytable (cost=0.00..14160.38 rows=306925 width=4) (actual time=0.140..575.580 rows=306925 loops=1) > Total runtime: 1013.657 ms > (3 rows) I assume you have random_page_cost dialled way down? The costs seem too low for the default random_page_cost. This query would usually generate a sort rather than an index scan. -- Gregory Stark EnterpriseDB http://www.enterprisedb.com