From: James Robinson <jlrobins@socialserve.com>
To: pgsql-sql@postgresql.org
Subject: Utility of recursive queries?
Date: Fri, 9 Apr 2004 10:33:57 -0400
Message-ID: <EF02401A-8A32-11D8-8620-000A9566A412@socialserve.com> (raw)
Would recursive queries be the trick to doing things like unwinding a
linked-list to either the head or tail, with:
create table list (
id int primary key,
parent int references list(id)
);
insert into list values (1, null); -- head of chain in list
insert into list values (2, 1); -- 1st child
insert into list values (3, 2); -- second child
Given a reference to id=3, would a recursive query be the trick to
unrolling the list to discover id=1 as the head using a SQL one-liner?
Is discovery possible in straight SQL w/o resorting to stored
procedures (or modifying the table schema to directly point)? And,
finally, would any potential recursive query implementation be
noticably more efficient that a straightforward implementation in
plpgsql, such as:
create or replace function find_head(int) returns int as '
DECLARE
cur_par INT;
prev_par INT;
BEGIN
prev_par := $1;
cur_par := parent from list where id = $1;
WHILE cur_par is not null LOOP
prev_par := cur_par;
cur_par := parent from list where id = prev_par;
END LOOP;
return prev_par;
END;
' language 'plpgsql';
----
James Robinson
Socialserve.com
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 from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-sql@postgresql.org
Cc: jlrobins@socialserve.com
Subject: Re: Utility of recursive queries?
In-Reply-To: <EF02401A-8A32-11D8-8620-000A9566A412@socialserve.com>
References: <EF02401A-8A32-11D8-8620-000A9566A412@socialserve.com>
* 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