dynamic sql query in postgres

postgresql execute sql string
postgresql dynamic table name
postgres execute
postgres dynamic where clause
dynamic update query in postgresql
postgresql function return dynamic table
postgresql dynamic ddl
postgresql dynamic filters

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

Link: string substitution with query result postgresql

How to implement Dynamic SQL in PostgreSQL 10, Another important use of dynamic SQL is to overcome the side effects of PL/​pgSQL caching, as queries executed using the EXECUTE  Another important use of dynamic SQL is to overcome the side effects of PL/pgSQL caching, as queries executed using the EXECUTE statement are not cached. Dynamic SQL is achieved via the EXECUTE statement. The EXECUTE statement accepts a string and simply evaluates it. The synopsis to execute a statement is given as follows:

CREATE OR REPLACE FUNCTION public.exec(
text)
RETURNS SETOF RECORD
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN 
    RETURN QUERY EXECUTE $1 ; 
END 
$BODY$;

usage:

select * from exec('select now()') as t(dt timestamptz)

dynamic sql query in postgres, 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. The standard approach to using dynamic SQL in PostgreSQL is plpgsql’s EXECUTE function, which takes a text argument as the SQL statement to execute. One technique fairly well-known on the #postgresql IRC channel is to create a function which essentially wraps the EXECUTE statement, commonly known as exec().

Try using

RETURN QUERY EXECUTE '<SQL Command>'

This will return data into form of table. You have to use this into stored function of PostgreSQL.

I have already created on full demonstration on custom filter and custom sorting using dynamic query of PostgreSQL. Please visit this url: http://www.dbrnd.com/2015/05/postgresql-dynamic-sql/

PostgreSQL: Dynamic SQL Function, If you've ever thought, “Hey, I could write a query to handle this,” then you're probably looking for dynamic SQL. The standard approach to using  Dynamic SQL. In many cases, the particular SQL statements that an application has to execute are known at the time the application is written. In some cases, however, the SQL statements are composed at run time or provided by an external source.

EXECUTE will work only on pl/pqsql environment.

instead of EXECUTE try with SELECT

 SELECT format('SELECT * from result_%s_table', quote_ident((select id from ids where condition = some_condition))

output would be the dynamic query.

How to use function parameters in dynamic SQL with EXECUTE , SQL injection in Postgres functions vs prepared queries. I removed unused variable id int; and the unused parameter organizationId text . I was trying to create a dynamic query, putting in my own date. date = dt.date(2018, 10, 30) query = ''' select * from table where date >= ''' + str(my_date) + ''' order by date ''' But, the query entirely ignores the condition when typing it this way. However, if you use the percent sign (%), you can insert the date correctly.

These all look more complicated than the OP's question. A different formatting should do the trick.. but it could absolutely the case that I don't understand.

From how I read OP's question, I think others in a similar situation may benefit from how I got it.

I am using Postgre on Redshift, and I ran into this issue and found a solution.

I was trying to create a dynamic query, putting in my own date.

date = dt.date(2018, 10, 30)

query = ''' select * from table where date >= ''' + str(my_date) + ''' order by date '''

But, the query entirely ignores the condition when typing it this way.

However, if you use the percent sign (%), you can insert the date correctly.

One correct way to write the above statement is:

query = ''' select * from table where date >= ''' + ''' '%s' ''' % my_date + ''' order by date '''

So, maybe this is helpful, or maybe it is not. I hope it helps at least one person in my situation!

Best wishes.

Postgres plpgsql, Use quote_ident() to avoid SQL injection or syntax errors. that's because Postgresql needs to be able to parse query on compiling the dynamic SQL statement. sql = 'RETURN QUERY SELECT * FROM. /*later*/ EXECUTE sql; In all cases without success. Ultimately I want to write a stored procedure that contains a dynamic sql statement and that returns the result set from the dynamic sql statement.

PostgreSQL : Documentation: 9.4: Basic Statements : Postgres , Write the query the same way you would write an SQL SELECT command, but Thus the command string can be dynamically created within the function to  1 Answer 1. You will need to use the PL/PgSQL EXECUTE statement, via a DO block or PL/PgSQL function (CREATE OR REPLACE FUNCTION LANGUAGE plpgsql). Dynamic SQL is not supported in the ordinary SQL dialect used by PostgreSQL, only in the procedural PL/PgSQL variant.

4.7 Dynamic SQL, EDB Postgres Advanced Server v9.4: EDB Postgres Advanced Server (EPAS) builds on open source PostgreSQL, the world's most advanced open-source  Dynamic SQL is an upgraded type of Structured Query Language (SQL) that not at all like standard (or static) SQL, encourages the programmed age and execution of program explanations. This can be useful when it is important to compose code that can change in accordance with fluctuating databases, conditions, or servers.

Postgres| PLSQL, This video will help you to run select query dynamically using any number of column, any table Duration: 7:23 Posted: Jul 12, 2018 Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM. For WITH queries, use PERFORM and then place the query in parentheses. (In this case, the query can only return one row.)

Comments
  • Just to complement, a DO block always returns void and accepts no parameters so I think the OP is restricted to a function.
  • @Clodoaldo Good point - they can execute the SELECT but it won't do them any good unless they were to do something really roundabout like SELECT ... INTO a temp table.
  • @CraigRinger Hi there, I know I am a little late to the party, but can you suggest any good tutorial for dynamic sql in postgreSQL ? I cannot find any. I want to create an all-in-one dynamic query. Check this question if you want. Thank you
  • "You cannot use dynamic SQL directly in PostgreSQL's SQL dialect." Well, as a matter of fact you can, at least using query_to_xml. See stackoverflow.com/a/38684225/3935325
  • This is simple and real good for day-by-day... Show how to use the dynamic query as an usual query!
  • The text of the dynamic query, sure, but it won't execute the query. See prior linked post.
  • yes i've gone through ur detailed dynamic qry execution, here just what i mentioned is EXECUTE will work only in pl/pqsql environment, and when i posted my answer i really didn't noticed ur response.
  • No worries. It just doesn't answer the question, which is how to execute dynamic SQL.
  • then the the above statement should be in pl/pqsql block, which i mentioned in first line itself.
  • I considered downvoting, because as said, this doesn't execute the block. BUT it's not hard to take the result of the query and feed it again as another query call, the dynamic content is trusted. So this solves the problem and avoids injection in theory.