Guide to Declaring Variables in PostgreSQL
PostgreSQL: Declaring Variables
In PostgreSQL, variables are often declared within functions or anonymous code blocks. They are used to store temporary data during the execution of a function or script. Variable declaration is primarily achieved through the PL/pgSQL procedural language.
This guide explains how to declare variables in PostgreSQL, provides syntax, and includes examples to help users leverage variables effectively in their queries and functions.
Syntax:
Variables in PostgreSQL are declared using the DECLARE keyword within the DO block or CREATE FUNCTION. Here's the basic syntax:
DO $$ DECLARE variable_name data_type [DEFAULT value]; BEGIN -- Statements using the variable END $$;
Example 1: Declaring and Using a Variable
Code:
-- Use an anonymous DO block to declare a variable
DO $$
DECLARE
employee_count INTEGER; -- Declare an integer variable
BEGIN
-- Assign a value to the variable using a SELECT statement
SELECT COUNT(*) INTO employee_count FROM employees;
-- Print the variable value
RAISE NOTICE 'Total employees: %', employee_count;
END $$;
Explanation:
- employee_count is declared as an INTEGER.
- The result of SELECT COUNT(*) is stored in employee_count using INTO.
- RAISE NOTICE prints the variable value.
1. Declaration:
2. Assignment:
3. Output:
Example 2: Using Variables in Functions
Code:
-- Create a function to calculate employee salaries
CREATE OR REPLACE FUNCTION calculate_bonus(salary_threshold NUMERIC)
RETURNS TABLE(employee_id INT, bonus NUMERIC) AS $$
DECLARE
bonus_rate NUMERIC := 0.10; -- Declare and initialize a variable
BEGIN
-- Use the variable in a query
RETURN QUERY
SELECT id, salary * bonus_rate AS bonus
FROM employees
WHERE salary > salary_threshold;
END $$ LANGUAGE plpgsql;
Explanation
- bonus_rate is declared and initialized with 0.10 (10% bonus rate).
- The RETURN QUERY uses the variable bonus_rate to calculate bonuses for employees with a salary above the threshold.
1. Variable Declaration:
2. Function Logic:
Example 3: Default Values in Variables
Code:
DO $$
DECLARE
tax_rate NUMERIC DEFAULT 0.05; -- Declare with a default value
total_salary NUMERIC;
BEGIN
-- Assign the sum of salaries to the variable
SELECT SUM(salary) INTO total_salary FROM employees;
-- Calculate total tax
RAISE NOTICE 'Total tax: %', total_salary * tax_rate;
END $$;
Explanation:
- tax_rate is initialized with a default value of 0.05.
- The total tax is calculated using the variable total_salary and tax_rate.
1. Default Initialization:
2. Computation:
Common Use Cases
1. Control Flow: Variables help manage control flow by storing intermediate results for loops or conditionals.
2. Dynamic Queries: Use variables to construct and execute dynamic SQL statements.
Additional Notes
- Scope: Variables declared within a DO block or function are local to that block/function.
- Type Casting: Ensure appropriate data types during declaration to avoid runtime errors.
All PostgreSQL Questions, Answers, and Code Snippets Collection.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/PostgreSQL/snippets/postgres-declare-variable.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics