Last Updated : 15 Jul, 2025
In PostgreSQL, constants are similar to variables but with a crucial difference: once their value is initialized, it cannot be altered. This immutability is beneficial for several reasons, enhancing both, the readability of SQL queries and reducing maintenance efforts.
Here we will look into the syntax, usage, and practical examples of constants in PostgreSQL to provide a clear understanding of their importance and operation.
Syntaxconstant_name CONSTANT data_type := expression;
Let's analyze the above syntax:
Let us take a look at some of the examples of Constants in PostgreSQL to better understand the concept.
Example 1: Calculating with ConstantsThe following example declares a constant named VAT for valued added tax and calculates the selling price from the net price:
DO $$
DECLARE
VAT CONSTANT NUMERIC := 0.1;
net_price NUMERIC := 20.5;
BEGIN
RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
END $$;
Output:
Now let's attempt to change the constant as below:
DO $$
DECLARE
VAT constant NUMERIC := 0.1;
net_price NUMERIC := 20.5;
BEGIN
RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
VAT := 0.05;
END $$;
As expected it raises an error as shown below:
Explanation: This example clearly demonstrates how constants can simplify calculations in financial operations by keeping the tax rate fixed and visible.
Example 2: Time-Dependent ConstantsIt is important to note that PostgreSQL evaluates the value for the constant when the block is entered at run-time, not compile-time as shown in the below example:
DO $$
DECLARE
start_at CONSTANT time := now();
BEGIN
RAISE NOTICE 'Start executing block at %', start_at;
END $$;
Output:
PostgreSQL evaluates the NOW() function every time we call the block. To prove it, we execute the block again:
Output: Each execution of this block will capture and display the time at which the block starts running, showing how constants can dynamically initialize based on the current state when the block is entered.
Important Points About PostgreSQL Constants
- Using constants can improve the performance of queries by allowing PostgreSQL's query planner to make optimizations based on the immutability of values.
- In complex procedures, using constants can simplify debugging and future maintenance. Since the value is set in one place, any changes required later need only be made once, reducing the risk of errors or inconsistencies.
- Unlike some other programming environments where constants must be defined with static values, PostgreSQL allows constants to be initialized dynamically using expressions or functions that are evaluated at run-time.
- Any attempt to reassign a value to a constant after its initial definition will result in a compilation error.
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