X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 759E69F9586 for ; Sat, 6 May 2006 10:56:07 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 85394-01 for ; Sat, 6 May 2006 10:55:47 -0300 (ADT) X-Greylist: delayed 00:05:04.810084 by SQLgrey- Received: from moutng.kundenserver.de (moutng.kundenserver.de [212.227.126.171]) by postgresql.org (Postfix) with ESMTP id EDC4D9F9431 for ; Sat, 6 May 2006 10:55:47 -0300 (ADT) Received: from [84.157.40.11] (helo=lunix.schabi.de) by mrelayeu.kundenserver.de (node=mrelayeu9) with ESMTP (Nemesis), id 0ML2xA-1FcNB22Qy7-0000g4; Sat, 06 May 2006 15:50:37 +0200 Received: from [127.0.0.1] (localhost [127.0.0.1]) by lunix.schabi.de (Postfix) with ESMTP id 059343741B; Sat, 6 May 2006 15:50:01 +0200 (CEST) Message-ID: <445CA989.60308@logix-tt.com> Date: Sat, 06 May 2006 15:50:01 +0200 From: Markus Schaber User-Agent: Mozilla Thunderbird 1.0.7 (X11/20051017) X-Accept-Language: de-DE, de, en-us, en MIME-Version: 1.0 To: =?ISO-8859-2?Q?Miroslav_=A9ulc?= CC: pgsql-sql@postgresql.org Subject: Re: Most efficient way to hard-sort records References: <445C5A94.4020907@startnet.cz> In-Reply-To: <445C5A94.4020907@startnet.cz> X-Enigmail-Version: 0.93.0.0 Content-Type: text/plain; charset=ISO-8859-2 Content-Transfer-Encoding: 8bit X-Provags-ID: kundenserver.de abuse@kundenserver.de login:a9554655f07a4e401310f2acfb43f5bf X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200605/64 X-Sequence-Number: 25095 Hi, Miroslav, Miroslav Šulc schrieb: > I have a table with cca 100,000 records. I need to hard-sort the records > by a key from second table. By hard-sorting I mean storing position of > each row in the main table. Here is what my tables look like: > > main_table: id, name, position > key_table: id, main_table_id, key, value > > Here is how I need to sort the records: > SELECT * FROM main_table > INNER JOIN key_table ON main_table.id = key_table.main_table_id > WHERE key = 'param' > ORDER BY value > > I currently collect all ids from main_table in sorted order and then > update the position field for each row in the main_table one-by-one. Is > there a better/faster/more efficient solution? Create an SQL function that selects the sort value from the key table when given id as parameter, and then create a functional index on the table, and CLUSTER the table on the index. Scratch-Code (untested): CREATE FUNCTION getvalue (ID int4) RETURNS int4 AS " SELECT value FROM key_table WHERE value=$1 LIMIT 1" LANGUAGE SQL STRICT; CREATE INDEX main_table_order_idx ON main_table (getvalue(id)); CLUSTER main_table_order_idx ON main_table; HTH, Markus