1

I have the following table:

test=# CREATE TABLE stmts(id SERIAL, selector VARCHAR(255));
CREATE TABLE
test=# INSERT INTO stmts(selector) VALUES('5 > 3'),('5 < 3');
INSERT 0 2
test=# SELECT selector FROM stmts;
 selector
----------
 5 > 3
 5 < 3
(2 rows)

I want to amend the select to be able to evaluate the value of the selector for each row, so desired effect is:

 selector, magic FROM stmts;
 selector | magic
--------------------
 5 > 3    | true
 5 < 3    | false
(2 rows)

It would be great if this was executed in the context of the row, so we can evaluate for example expression id = 5, etc.

Is this even possible?

klin
  • 112,967
  • 15
  • 204
  • 232
kulak
  • 852
  • 7
  • 16
  • I found a similar question from the past : http://stackoverflow.com/questions/7433201/are-there-any-way-to-execute-a-query-inside-the-string-value-like-eval-in-post – Guillaume F. Nov 19 '15 at 20:35

1 Answers1

0

You can do this dynamically in a plpgsql function:

create or replace function eval_bool(expr text)
returns boolean language plpgsql as $$
declare
    rslt boolean;
begin
    execute format('select %s', expr) into rslt;
    return rslt;
end $$;

select id, selector, eval_bool(selector) 
from stmts;

 id | selector | eval_bool 
----+----------+-----------
  1 | 5 > 3    | t
  2 | 5 < 3    | f
(2 rows)
klin
  • 112,967
  • 15
  • 204
  • 232