title: Pass a Table Column Name in a PostgreSQL Function
body: <p>I've read some posts about using table column names in a PostgreSQL function but I couldn't make it work for me.</p>
  
  <p>I have this simple function</p>
  
  <pre><code>DROP FUNCTION IF EXISTS public.benchmark(CHARACTER VARYING, CHARACTER VARYING, BIGINT, BIGINT, BIGINT);
  CREATE OR REPLACE FUNCTION benchmark(params CHARACTER VARYING, colName CHARACTER VARYING, idFrom BIGINT, idTo BIGINT, testNumber BIGINT) RETURNS SETOF RECORD AS $$
  DECLARE
      elemArray TEXT[] := ARRAY(SELECT colName FROM public.test WHERE test.id BETWEEN idFrom AND idTo);
      selectedElem RECORD;
      elem TEXT;
  BEGIN
      FOREACH elem IN ARRAY elemArray LOOP
          raise notice 'elem Value: %', elem;
          SELECT elem INTO selectedElem;
          RETURN NEXT selectedElem;
      END LOOP;
  END;
  $$ LANGUAGE plpgsql;
  </code></pre>
  
  <p>When I execute it with</p>
  
  <pre><code>SELECT * FROM public.benchmark('ad','name',1,2,1) AS x(Item TEXT);
  </code></pre>
  
  <p>I get</p>
  
  <p><a href="https://i.stack.imgur.com/LZKSi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LZKSi.png" alt="enter image description here"></a></p>
  
  <p>and what I should be getting are the <strong>name</strong> column values between <strong>idFrom</strong> and <strong>idTo</strong>. How can I use the colName variable as an actual column name in <code>elemArray TEXT[] := ARRAY(SELECT colName FROM public.test WHERE test.id BETWEEN idFrom AND idTo);</code></p>