This PostgreSQL tutorial explains How To Declare A Variable In PostgreSQL with syntax and examples.
By declaring PostgreSQL Variables, sometimes we may need to use the values we receive from outside in operations such as insert, update and delete.
We can use variables when writing a Stored Procedure or Function.
First, let’s talk about the do method.
1 2 3 4 5 6 | DO $$ DECLARE a int := 1; BEGIN RAISE NOTICE ' entered variable : %', a ; END $$; |
To declare a variable, we need to start with DO$$.
In the declare section or between the “begin end” blocks, we write the name and data type of our variable and define its value with “:=”.
The output of the variable can be printed on the screen by typing the variable declared with the ‘%’ sign after the RAISE NOTICE.
In RAISE NOTICE, after writing what you want to write before the variable inside the quotation marks, you need to write the % sign since we are using a single variable.
You can use it for multiple variables as follows.
Another different use is to declare session-based variables.
Example usage is as follows.
In the above example, it will bring the record in the veliler table according to the variable value entered.