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:
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
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:
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
All PostgreSQL Questions, Answers, and Code Snippets Collection.
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