Sample Header Ad - 728x90

Postgres - how to 'print' a variable within a function (similar to python)?

0 votes
1 answer
5460 views
How to print(var) in postgres like python? Given the following code:
CREATE OR REPLACE FUNCTION custom_sum(c1 integer, c2 integer)
RETURNS integer AS 
$$
    SELECT c1 + c2;
$$ 
LANGUAGE SQL;

CREATE aggregate agg_custom_sum(integer) (
    sfunc = custom_sum,
    stype = integer,
    initcond = 0
);

DROP TABLE IF EXISTS aggcheck;
CREATE TABLE aggcheck AS 
SELECT x FROM generate_series(1, 3) AS g(x);

SELECT agg_custom_sum(x) FROM aggcheck;
How can I print the values of c1, c2 to the terminal when running? Eg (I'm aware this won't work - it's python syntax - hopefully communicates the sort of usage I'm after though):
CREATE OR REPLACE FUNCTION custom_sum(c1 integer, c2 integer)
RETURNS integer AS 
$$
    print(f"c1 = {c1}, c2 = {c2}"); 
    SELECT c1 + c2;
$$ 
LANGUAGE SQL;
If it makes much difference - I'm calling this using \i script.sql from within a psql session. If there are any links to debugging approaches more generally (eg breakpoing, try/catch, writing to a file) they would be appreciated, though not necessary to answer this question.
Asked by baxx (326 rep)
Jan 29, 2023, 07:27 PM
Last activity: Jan 29, 2023, 11:23 PM