The PL/pgSQL version can look like this:
CREATE FUNCTION account_count_in(_branch_city text)
RETURNS int
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN (
SELECT count(DISTINCT a.account_number)::int
FROM account a
NATURAL JOIN branch b
WHERE b.branch_city = _branch_city
);
END
$func$;
Call:
SELECT account_count_in('Albany');
Avoid naming collisions. Make the parameter name unique or table-qualify columns in the query. I did both.
Just RETURN
the result for a simple query like this.
The function is declared to return integer
. Make sure the return type matches by casting the bigint
to int
.
NATURAL JOIN
is short syntax, but it may not be the safest form. Later changes to underlying tables can easily break this. Better to join on column names explicitly.
PERFORM
is only valid in PL/pgSQL functions, not in SQL functions and not useful here.