Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RETURN QUERY vs RETURN QUERY EXECUTE

Tags:

postgresql

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;

?

like image 229
countryroadscat Avatar asked Sep 28 '16 06:09

countryroadscat


People also ask

What is a return query?

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.

What is execute in PostgreSQL?

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.

How do I return a query in PostgreSQL?

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.

What is $$ in PostgreSQL?

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).


1 Answers

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.

like image 133
Laurenz Albe Avatar answered Oct 21 '22 01:10

Laurenz Albe