it looks like you are doing strange joins with the SQL. rather than using strange-and-wonderful postgres specific functions, i would re-evaluate the design of the database....as from a cursory glance at the sql, you seem to be doing things of a hierarchial/recursive nature. not something relational databases are designed for.