Re: Most efficient way to hard-sort records

From: Markus Schaber <schabi(at)logix-tt(dot)com>
To: Miroslav Šulc <miroslav(dot)sulc(at)startnet(dot)cz>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Most efficient way to hard-sort records
Date: 2006-05-06 13:50:01
Message-ID: 445CA989.60308@logix-tt.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Bruno Wolff III 2006-05-06 15:39:16 Re: Returning String as Integer
Previous Message Miroslav Šulc 2006-05-06 08:13:08 Most efficient way to hard-sort records