Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 9E547632481 for ; Mon, 19 Jul 2010 12:09:45 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 80149-01 for ; Mon, 19 Jul 2010 15:09:31 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id 47BD06321A0 for ; Mon, 19 Jul 2010 12:09:30 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1Oary8-0001QR-Tv for pgsql-performance@postgresql.org; Mon, 19 Jul 2010 17:09:24 +0200 Received: from lara.cc.fer.hr ([161.53.72.113]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Mon, 19 Jul 2010 17:09:24 +0200 Received: from ivoras by lara.cc.fer.hr with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Mon, 19 Jul 2010 17:09:24 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-performance@postgresql.org From: Ivan Voras Subject: Big field, limiting and ordering Date: Mon, 19 Jul 2010 17:09:32 +0200 Lines: 31 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: lara.cc.fer.hr User-Agent: Mozilla/5.0 (X11; U; FreeBSD amd64; en-US; rv:1.9.1.9) Gecko/20100518 Thunderbird/3.0.4 X-Enigmail-Version: 1.0.1 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201007/285 X-Sequence-Number: 39674 Hello, I don't think this is generally solvable but maybe it is so here goes. The original situation was this: SELECT something, big_field, complex_function(big_field), rank FROM t1 UNION ALL SELECT something, big_field, complex_function(big_field), rank from t2 ORDER BY rank LIMIT small_number; This query first fetches all big_field datums and does all complex_function() calculations on them, then orders then by rank, even though I actually need only small_number of records. There are two problems here: first, selecting for all big_field values requires a lot of memory, which is unacceptable, and then, running complex_function() on all of them takes too long. I did get rid of unnecessary complex_function() calculations by nesting queries like: SELECT something, big_field, complex_function(big_field), rank FROM (SELECT original_query_without_complex_function_but_with_big_field ORDER BY rank LIMIT small_number); but this still leaves gathering all the big_field datum from the original query. I cannot pull big_field out from this subquery because it comes from UNION of tables. Any suggestions? (I cannot limit big_field with substring() to reduce memory usage because it messes up complex_function()).