X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id A00829DC97F for ; Fri, 17 Feb 2006 20:51:30 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 04401-04 for ; Fri, 17 Feb 2006 20:51:33 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from stark.xeocode.com (stark.xeocode.com [216.58.44.227]) by postgresql.org (Postfix) with ESMTP id 00C559DC869 for ; Fri, 17 Feb 2006 20:51:27 -0400 (AST) Received: from localhost ([127.0.0.1] helo=stark.xeocode.com) by stark.xeocode.com with smtp (Exim 3.36 #1 (Debian)) id 1FAGJr-0008Ls-00; Fri, 17 Feb 2006 19:51:27 -0500 To: Jan Danielsson Cc: pgsql-sql@postgresql.org Subject: Re: two count columns? References: <43F662C4.9070402@gmail.com> In-Reply-To: <43F662C4.9070402@gmail.com> From: Greg Stark Organization: The Emacs Conspiracy; member since 1992 Date: 17 Feb 2006 19:51:27 -0500 Message-ID: <87mzgp1oc0.fsf@stark.xeocode.com> Lines: 44 User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.131 required=5 tests=[AWL=0.131] X-Spam-Score: 0.131 X-Spam-Level: X-Archive-Number: 200602/223 X-Sequence-Number: 24233 Jan Danielsson writes: > select from_ip, count(from_ip) as entries, count(select * from log where > ...) as tot_entries, max(ts)::timestamp(0) as last_access from log where > to_port=22 and direction='in' group by from_ip select from_ip, count(from_ip) as entries, (select count(*) from log as l where l.from_ip = log.from_ip ) as tot_entries, max(ts) as last_access from log where to_port=22 and direction='in group by from_ip expect it to be pretty slow though. For every from_ip it has to look up every other entry with that from_ip. > Thankful for any hints or tips. There is a trick you could use to make it faster but it gets cumbersome and pretty tricky to use when you're doing more than one thing at a time: select from_ip sum(case when to_port=22 and direction='in' then 1 else 0 end) as entries, count(*) as tot_entries, max(case when to_port=22 and direction='in' then ts::timestamp(0) else null end) as last_access from log group by from_ip having entries > 0 Note that in either case you might want to look at ANALYZE results for the query and try raising work_mem for this query using SET until you see the plan using a hash aggregate. If it can use a hash aggregate for your query (more likely for the first query than the second) without swapping it'll be faster than sorting. -- greg