dynamic sql query in postgres

EXECUTE ... USING only works in PL/PgSQL – ie within functions or DO blocks written in the PL/PgSQL language. It does not work in plain SQL; the EXECUTE in plain SQL is completely different, for executing prepared statements. You cannot use dynamic SQL directly in PostgreSQL’s SQL dialect.

Compare:

See the 2nd last par in my prior answer.


In addition to not running except in PL/PgSQL your SQL statement is wrong, it won’t do what you expect. If (select id from ids where condition = some_condition) returns say 42, the statement would fail if id is an integer. If it’s cast to text you’d get:

EXECUTE format('SELECT * from result_%s_table', quote_ident('42'));
EXECUTE format('SELECT * from result_%s_table', '"42"');
EXECUTE 'SELECT * from result_"42"_table';

That’s invalid. You actually want result_42_table or "result_42_table". You’d have to write something more like:

EXECUTE format('SELECT * from %s', quote_ident('result_'||(select id from ids where condition = some_condition)||'_table'))

… if you must use quote_ident.

Leave a Comment