Calling functions with exec instead of select

PostgresqlPsql

Postgresql Problem Overview


Is the default way of calling a function select * from my_function()?

I ask because I have built a function that doesn't return anything, just inserts data into a table and (coming from a SQL Server background) it "feels" strange to call it with select * from...

I was expecting something like exec my_function()

Postgresql Solutions


Solution 1 - Postgresql

use PERFORM statement - http://www.postgresql.org/docs/current/static/plpgsql-statements.html

> Sometimes it is useful to evaluate an expression or SELECT query but > discard the result, for example when calling a function that has > side-effects but no useful result value. To do this in PL/pgSQL, use > the PERFORM statement

so it's just

DO $$ BEGIN
    PERFORM my_function();
END $$;

Solution 2 - Postgresql

PostgreSQL 11:

PostgreSQL 11 supports true stored procedures as pointed out by @AbdisamadKhalif . They support in-procedure transaction control.

Older versions:

Yes, that's the standard way, and yes it's weird.

Usually you'd write such functions as stored procedures and invoke them with the CALL or EXECUTE command. PostgreSQL does not support true stored procedures (multiple result sets, autonomous transactions, and all that) though, only sql-callable user-defined functions.

So the workaround is to SELECT function_name() using the PostgreSQL extension syntax that omits FROM, or SELECT 1 FROM function_name(); to be (somewhat) more standard.

The ODBC driver, JDBC driver, etc understand the {call func_name()} escape syntax and automatically translate it to an underlying SELECT.

Solution 3 - Postgresql

You will use from when the function returns a set. If the function returns void just do

select my_function();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiegoView Question on Stackoverflow
Solution 1 - PostgresqlRoman PekarView Answer on Stackoverflow
Solution 2 - PostgresqlCraig RingerView Answer on Stackoverflow
Solution 3 - PostgresqlClodoaldo NetoView Answer on Stackoverflow