I was attempting to use Dynamic SQL to run some queries in postgres.
Example:
EXECUTE format('SELECT * from result_%s_table', quote_ident((select id from ids where condition = some_condition)))
I have to query a table, which is of the form result_%s_table wherein, I need to substitute the correct table name (an id) from an another table.
I get the error ERROR: prepared statement "format" does not exist
EXECUTE ... USINGonly works in PL/PgSQL – ie within functions orDOblocks written in the PL/PgSQL language. It does not work in plain SQL; theEXECUTEin plain SQL is completely different, for executing prepared statements. You cannot use dynamic SQL directly in PostgreSQL’s SQL dialect.Compare:
EXECUTE ... USING; toEXECUTESee 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 say42, the statement would fail ifidis an integer. If it’s cast to text you’d get:That’s invalid. You actually want
result_42_tableor"result_42_table". You’d have to write something more like:… if you must use
quote_ident.