Great! Next, we'll learn about variables in PL/pgSQL.
What is a variable? A variable stores a value that can be modified and used inside a block of code or function. Before we use a variable, we must declare it in the declaration section of a PL/pgSQL function. The declaration section starts with
DECLARE keyword and ends with the
BEGIN keyword of the function body block.
CREATE FUNCTION get_monthly_salary(salary decimal)
RETURNS decimal AS $$
months integer := 12;
monthly_salary := salary/months;
RAISE NOTICE 'Monthly salary is %', monthly_salary;
return round(monthly_salary, 4);
$$ LANGUAGE plpgsql;
In the example above, we declared two variables (after the
monthly_salary. Variables must have a specific data type associated with them. In our case,
decimal. When we declare a new variable, we put the type of the variable after its name.
months variable has a value of 12 assigned. We use the
:= symbol, followed by the value.
monthly_salary variable is declared in the
DECLARE part of the function, but its value is not assigned – its initial value is
The assignment for the
monthly_salary variable is done in the function body.