pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Bryce Nesbitt <bryce2@obviously.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: Sequential scan evaluating function for each row, seemingly needlessly
Date: Tue, 07 Sep 2010 16:31:39 -0400
Message-ID: <25196.1283891499@sss.pgh.pa.us> (raw)
In-Reply-To: <4C868F49.5050601@obviously.com>
References: <4C868F49.5050601@obviously.com>

Bryce Nesbitt <bryce2@obviously.com> 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



view thread (2+ messages)

Message-ID: <25196.1283891499@sss.pgh.pa.us>
Permalink:  ../25196.1283891499@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/25196.1283891499@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, bryce2@obviously.com
  Subject: Re: Sequential scan evaluating function for each row, seemingly needlessly
  In-Reply-To: <25196.1283891499@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox