Disambiguating variables, or a “this” keyword, for plpgsql

Derry Hamilton - 07/11/2019

Some names, like account_number, or customer_id crop up in a lot of places, and when you’re juggling tables inside a plpgsql function, it can be a bit of a pain. Postgres allows you to disambiguate names by qualifying them with the function name, or the block name.

CREATE FUNCTION app.a_long_function_name(id integer)
RETURNS integer
LANGUAGE plpgsql
AS $$
BEGIN
    return 27 + a_long_function_name.id;
END;
$$

CREATE FUNCTION app.a_long_function_name(id integer)
RETURNS integer
LANGUAGE plpgsql
AS $$
<<this>>
DECLARE
    id alias for id;
BEGIN
    return 27 + this.id;
END;
$$