Postgresql – how to declare a variable

Syntax:

DECLARE variable_name datatype;

A variable declaration requires a variable name and a data type.

Example:

DECLARE v_cityname varchar;
DECLARE v_age int;

You can optionally specify a default value to the variable.

DECLARE v_countryname varchar() DEFAULT 'USA';
DECLARE v_countryname varchar() := 'USA';

The ‘CONSTANT’ keyword, if specified, will treat the variable value as constant once assigned. A variable that is declared as constant cannot be over written.

Example:

DECLARE v_age CONSTANT int;
See also  Postgresql - How to get current day, month, year from date