Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id B21F363687E for ; Tue, 7 Sep 2010 17:41:32 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 44854-01-3 for ; Tue, 7 Sep 2010 20:41:24 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 8FF6F63717C for ; Tue, 7 Sep 2010 17:31:42 -0300 (ADT) 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 o87KVd4J025197; Tue, 7 Sep 2010 16:31:39 -0400 (EDT) To: Bryce Nesbitt cc: pgsql-sql@postgresql.org Subject: Re: Sequential scan evaluating function for each row, seemingly needlessly In-reply-to: <4C868F49.5050601@obviously.com> References: <4C868F49.5050601@obviously.com> Comments: In-reply-to Bryce Nesbitt message dated "Tue, 07 Sep 2010 12:15:21 -0700" Date: Tue, 07 Sep 2010 16:31:39 -0400 Message-ID: <25196.1283891499@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201009/15 X-Sequence-Number: 34546 Bryce Nesbitt writes: > On psql 8.3.9, I ran a limited query limited to 5 results. There was a > moderately expensive function call > which I expected to be called 5 times, but was apparently called for > each row of the sequential scan. Why? Given the plan: > Limit (cost=19654.53..19654.54 rows=5 width=12) (actual > time=10001.976..10001.990 rows=5 loops=1) > -> Sort (cost=19654.53..19826.16 rows=68651 width=12) (actual > time=10001.972..10001.976 rows=5 loops=1) > Sort Key: add_date > Sort Method: top-N heapsort Memory: 25kB > -> Seq Scan on extractq (cost=0.00..18514.26 rows=68651 > width=12) (actual time=19.145..9770.689 rows=73550 loops=1) > Total runtime: 10002.150 ms > (6 rows) any interesting work is going to be done at the seqscan level. Sort just sorts, and Limit just limits; neither do any user-defined calculations. So yeah, your functions got run for every row of the table. (This isn't totally a PG aberration, btw: if you read the SQL spec closely you'll discover that ORDER BY is defined to happen after any calculations specified in the SELECT list.) You could try something like select my_expensive_function(...), etc, etc from (select * from some-tables order by foo limit n) ss; where the inner select list just pulls the columns you'll need in the outer calculations. regards, tom lane