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 VariablesSyntax
The following illustrates the syntax for declaring a variable:
variable_name data_type [:= expression];
Let's analyze the above syntax:
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 UsageDO $$
DECLARE
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 $$;
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.
DO $$
DECLARE
created_at time := NOW();
BEGIN
RAISE NOTICE '%', created_at;
PERFORM pg_sleep(10);
RAISE NOTICE '%', created_at;
END $$;
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.
NULL
. 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4