I have the following function in Postgres:
CREATE OR REPLACE FUNCTION point_total(user_id integer, gametime date)
RETURNS bigint AS
$BODY$
SELECT sum(points) AS result
FROM picks
WHERE user_id = $1
AND picks.gametime > $2
AND points IS NOT NULL;
$BODY$
LANGUAGE sql VOLATILE;
It works correctly, but when a user starts out and has no points, it very reasonably returns NULL. How can I modify it so that it returns 0 instead.
Changing the body of the function to that below results in an “ERROR: syntax error at or near “IF”.
SELECT sum(points) AS result
FROM picks
WHERE user_id = $1
AND picks.gametime > $2
AND points IS NOT NULL;
IF result IS NULL
SELECT 0 AS result;
END;
You need to change the language from
sqltoplpgsqlif you want to use the procedural features of PL/pgSQL. The function body changes, too.Be aware that all parameter names are visible in the function body, including all levels of SQL statements. If you create a naming conflict, you may need to table-qualify column names like this:
table.col, to avoid confusion. Since you refer to function parameters by positional reference ($n) anyway, I just removed parameter names to make it work.Finally,
THENwas missing in theIFstatement – the immediate cause of the error message.One could use COALESCE to substitute for
NULLvalues. But that only works if there is at least one resulting row.COALESCEcan’t fix "no row" it can only replace actualNULLvalues.There are several ways to cover all
NULLcases. In plpgsql functions:Or you can enclose the whole query in a
COALESCEexpression in an outerSELECT. "No row" from the innerSELECTresults in aNULLin the expression. Work as plain SQL, or you can wrap it in an sql function:Related answer:
Concerning naming conflicts
One problem was the naming conflict most likely. There have been major changes in version 9.0. I quote the release notes:
Later versions have refined the behavior. In obvious spots the right alternative is picked automatically. Reduces the potential for conflicts, but it’s still there. The advice still applies in Postgres 9.3.