PostgreSQL Variables (original) (raw)

Last Updated : 15 Jul, 2025

**PostgreSQL, one of the most powerful and advanced open-source relational database management systems, provides robust support for **procedural programming through its **PL/pgSQL language. A fundamental aspect of PL/pgSQL is the use of **variables that play a crucial role in storing temporary data and facilitating complex computations within database functions and procedures.

Let us better understand the Variables in **PostgreSQL to better understand the concept.

PostgreSQL Variables

**Syntax

The following illustrates the syntax for declaring a variable:

variable_name data_type [:= expression];

Let's analyze the above syntax:

Examples of PostgreSQL Variables

Let us take a look at some of the examples of Variables in PostgreSQL to better understand the concept.

**Example 1: Basic Variable Declaration and Usage

DO DECLAREcounterINTEGER:=1;firstnameVARCHAR(50):=′John′;lastnameVARCHAR(50):=′Doe′;paymentNUMERIC(11,2):=20.5;BEGINRAISENOTICE′ENDDECLARE
counter INTEGER := 1;
first_name VARCHAR(50) := 'John';
last_name VARCHAR(50) := 'Doe';
payment NUMERIC(11,2) := 20.5;
BEGIN
RAISE NOTICE '% % % has been paid % USD', counter, first_name, last_name, payment;
END
DECLAREcounterINTEGER:=1;firstnameVARCHAR(50):=John;lastnameVARCHAR(50):=Doe;paymentNUMERIC(11,2):=20.5;BEGINRAISENOTICEEND
;

**Output:

Explanation: In this example, we declared four variables: 'counter', 'first_name', 'last_name', and 'payment'. Each variable is initialized with a specific value. The '**RAISE NOTICE' **statement is used to display the values of these variables.

**Example 2: Using System Functions with Variables

DO DECLAREcreatedattime:=NOW();BEGINRAISENOTICE′PERFORMpgsleep(10);RAISENOTICE′ENDDECLARE
created_at time := NOW();
BEGIN
RAISE NOTICE '%', created_at;
PERFORM pg_sleep(10);
RAISE NOTICE '%', created_at;
END
DECLAREcreatedattime:=NOW();BEGINRAISENOTICEPERFORMpgsleep(10);RAISENOTICEEND
;

**Output:

*Explanation: In this example, we declared a variable '*created_at'**and initialized it with the current time using the NOW() *function. The '*pg_sleep(10)'**function pauses the execution for 10 seconds.

The 'RAISE NOTICE' statements display the value of '**created_at'**before and after the pause, showing that the time remains the same as it was initialized once.

Important Points About PostgreSQL Variables

Conclusion

In conclusion, **PostgreSQL variables are an integral part of developing efficient and dynamic database applications. Mastering the syntax for **declaring variables in PostgreSQL not only enhances the functionality of database procedures but also contributes to cleaner, more maintainable code by allowing developers to build robust applications that meet modern data processing needs.