X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id B068656622 for ; Wed, 16 Mar 2005 17:58:57 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 76048-07 for ; Wed, 16 Mar 2005 17:58:45 +0000 (GMT) Received: from stan.aopsys (aopsysadsl.net1.nerim.net [62.212.101.94]) by svr1.postgresql.org (Postfix) with ESMTP id 756A6565AE for ; Wed, 16 Mar 2005 17:58:43 +0000 (GMT) Received: from [127.0.0.1] (helo=localhost ident=laurent) by stan.aopsys with esmtp (Exim 4.44) id 1DBcmx-0001Oz-QB for pgsql-performance@postgresql.org; Wed, 16 Mar 2005 18:58:35 +0100 To: pgsql-performance@postgresql.org Subject: Speeding up select distinct From: Laurent Martelli Organization: AOPSYS Date: Wed, 16 Mar 2005 18:58:35 +0100 Message-ID: <87k6o74gms.fsf@stan.aopsys> User-Agent: Gnus/5.1007 (Gnus v5.10.7) Emacs/20.7 (gnu/linux) MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.05 tagged_above=0 required=5 tests=FORGED_RCVD_HELO X-Spam-Level: X-Archive-Number: 200503/329 X-Sequence-Number: 11034 Consider this query: SELECT distinct owner from pictures; Unique (cost=361.18..382.53 rows=21 width=4) (actual time=14.197..17.639 rows=21 loops=1) -> Sort (cost=361.18..371.86 rows=4270 width=4) (actual time=14.188..15.450 rows=4270 loops=1) Sort Key: "owner" -> Seq Scan on pictures (cost=0.00..103.70 rows=4270 width=4) (actual time=0.012..5.795 rows=4270 loops=1) Total runtime: 19.147 ms I thought that 19ms to return 20 rows out of a 4000 rows table so I added an index: CREATE INDEX pictures_owner ON pictures (owner); It gives a slight improvement: Unique (cost=0.00..243.95 rows=21 width=4) (actual time=0.024..10.293 rows=21 loops=1) -> Index Scan using pictures_owner on pictures (cost=0.00..233.27 rows=4270 width=4) (actual time=0.022..8.227 rows=4270 loops=1) Total runtime: 10.369 ms But still, it's a lot for 20 rows. I looked at other type of indexes, but they seem to either not give beter perfs or be irrelevant. Any ideas, apart from more or less manually maintaining a list of distinct owners in another table ? -- Laurent Martelli laurent@aopsys.com Java Aspect Components http://www.aopsys.com/ http://jac.objectweb.org