PostgreSQL 39.6. Control Structures: RETURN QUERY has a variant RETURN QUERY EXECUTE, which specifies the query to be executed dynamically. Parameter expressions can be inserted into the computed query string via USING, in just the same way as in the EXECUTE command.
But what means dynamically?
What is a difference between these two statements (inside function with func_param
parameter):
RETURN QUERY SELECT * FROM foo WHERE foo_col = func_param;
and
RETURN QUERY EXECUTE 'SELECT * FROM foo WHERE foo_col = $1' USING func_param;
?
RETURN QUERY appends the results of executing a query to the function's result set. RETURN NEXT and RETURN QUERY can be freely intermixed in a single set-returning function, in which case their results will be concatenated.
The PostgreSQL EXECUTE command prepares and runs commands dynamically. The EXECUTE command can also run DDL statements and retrieve data using SQL commands. Similar to SQL Server, you can use the PostgreSQL EXECUTE command with bind variables.
To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ). In the function, we return a query that is a result of a SELECT statement.
It can be used to replace single quotes enclosing string literals (constants) anywhere in SQL scripts. The body of a function happens to be such a string literal. Dollar-quoting is a PostgreSQL-specific substitute for single quotes to avoid escaping of nested single quotes (recursively).
The difference between these two examples is that in the first one, the query plan can be retained and reused for future executions in the same database session.
In the second example, the query will be planned every time the function is executed.
The advantage of the first example is that you save planning time if the function is executed repeatedly. From the sixth execution on, PostgreSQL may choose to use a generic plan (see the documentation) which will be use for all future executions in the same database session.
The second example is only useful if the chosen generic plan proves bad, and you'd rather have PostgreSQL replan the query every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With