 <p>To overcome the "<em>ERROR: query has no destination for result data</em>" error you don't need dynamic SQL.</p> <p>You can <a href="https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW" rel="nofollow">select into a variable directly</a>:</p> <pre><code>select parentid into parent from account where childid = child_id; </code></pre> <hr> <p>But you can simplify your function by using a <a href="https://www.postgresql.org/docs/current/static/queries-with.html" rel="nofollow">recursive CTE</a> and a SQL function. That will perform a lot better especially with a large number of levels:</p> <pre><code>create or replace function build_mp(child_id text) returns text[] language sql as $$ with recursive all_levels (childid, parentid, level) as ( select childid, parentid, 1 from account where childid = child_id union all select c.childid, c.parentid, p.level + 1 from account c join all_levels p on p.parentid = c.childid ) select array_agg(childid order by level) from all_levels; $$; </code></pre>