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 7A1919FA42A for ; Sun, 7 May 2006 03:55:35 -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 57367-01 for ; Sun, 7 May 2006 03:55:30 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from coe.tamu.edu (edsun.coe.tamu.edu [165.91.232.6]) by postgresql.org (Postfix) with ESMTP id 945199FA32D for ; Sun, 7 May 2006 03:55:29 -0300 (ADT) Received: (from root@localhost) by bruner.coe.tamu.edu (8.13.1/8.13.1) id k476p7Ku002341; Sun, 7 May 2006 01:51:07 -0500 Received: from coe.tamu.edu (coe.tamu.edu [165.91.232.6]) by coe.tamu.edu (8.11.7p2+Sun/8.12.11) with ESMTP id k476rlq27549; Sun, 7 May 2006 01:53:47 -0500 (CDT) Date: Sun, 7 May 2006 01:53:46 -0500 (CDT) From: "Ben K." To: =?ISO-8859-2?Q?Miroslav_=A9ulc?= cc: pgsql-sql@postgresql.org Subject: Re: Most efficient way to hard-sort records In-Reply-To: <445C5A94.4020907@startnet.cz> Message-ID: References: <445C5A94.4020907@startnet.cz> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed X-Virus-Scanned: by AMaViS 0.3.12 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200605/75 X-Sequence-Number: 25106 > 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? A cheap solution if you don't care about the position value as long as sort order is ok. 1) # SELECT main_table.id into temp_table FROM main_table INNER JOIN key_table ON main_table.id = key_table.main_table_id ORDER BY value; 2) # update main_table set position = (select oid from temp_table where id = main_table.id ); I guess I'll get a set of consecutive oids by this. You can make the number begin at arbitrary number, by 2-a) # update main_table set position = ( (select oid::int4 from temp_table where id = main_table.id ) - (select min(oid::int4) from temp_table) + 1) ; I read that oid wraps around (after ~ billions) so you might want to check your current oid. Regards, Ben K. Developer http://benix.tamu.edu