Search code examples
sqlpostgresqlrecursive-query

Is it possible to make a recursive SQL query?


I have a table similar to this:

CREATE TABLE example (
  id integer primary key,
  name char(200),
  parentid integer,
  value integer);

I can use the parentid field to arrange data into a tree structure.

Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?

UPDATE: I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.


Solution

  • There are a few ways to do what you need in PostgreSQL.

    Something like this:

    create or replace function example_subtree (integer)
    returns setof example as
    'declare results record;
             child record;
     begin
      select into results * from example where parent_id = $1;
      if found then
        return next results;
        for child in select id from example
                      where parent_id = $1
          loop
            for temp in select * from example_subtree(child.id)
            loop
              return next temp;
            end loop;
          end loop;
      end if;
      return null;
    end;' language 'plpgsql';
    
    select sum(value) as value_sum
      from example_subtree(1234);