PostgreSQL – Record Type Variable
Last Updated :
21 Oct, 2024
In PostgreSQL, record-type variables provide a dynamic and flexible way to handle result sets that don’t have a predefined structure. Unlike row-type variables, PostgreSQL record-type variables can change their structure after being assigned a new row, making them highly versatile for dynamic SQL operations.
This article will explore how to declare and use record-type variables in PostgreSQL, including practical examples with the SELECT INTO statement and FOR loop.
Declaring a Record Type Variable in PostgreSQL
Let us get a better understanding of the Record type variable in PostgreSQL from this article. We can declare a record-type variable by simply using a variable name followed by the record keyword. A record-type variable can hold one row of data from a result set, and we can access its fields using dot notation. If we try to access a field before assigning a row to the record variable, we will encounter an error.
Syntax:
variable_name record;
Syntax for Accessing Fields in Record Type Variable
We can use the dot notation (.) to access any field from the record type variable. It is important to note that we must assign a record type variable before accessing its contents else, we will get an error.
Syntax:
record_variable.field_name;
Example of Record Type Variable in PostgreSQL
Let us take a look at some of the examples of Record Type Variables in PostgreSQL to better understand the concept. But first, we create a sample table using the below commands to perform examples:
Query:
CREATE TABLE employees (
employee_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
manager_id INT
);
INSERT INTO employees (
employee_id,
full_name,
manager_id
)
VALUES
(1, 'M.S Dhoni', NULL),
(2, 'Sachin Tendulkar', 1),
(3, 'R. Sharma', 1),
(4, 'S. Raina', 1),
(5, 'B. Kumar', 1),
(6, 'Y. Singh', 2),
(7, 'Virender Sehwag ', 2),
(8, 'Ajinkya Rahane', 2),
(9, 'Shikhar Dhawan', 2),
(10, 'Mohammed Shami', 3),
(11, 'Shreyas Iyer', 3),
(12, 'Mayank Agarwal', 3),
(13, 'K. L. Rahul', 3),
(14, 'Hardik Pandya', 4),
(15, 'Dinesh Karthik', 4),
(16, 'Jasprit Bumrah', 7),
(17, 'Kuldeep Yadav', 7),
(18, 'Yuzvendra Chahal', 8),
(19, 'Rishabh Pant', 8),
(20, 'Sanju Samson', 8);
Output

employees table
Example 1: Using Record Type Variables with SELECT INTO
The following query demonstrates how to use record type variables in conjunction with the SELECT INTO
statement. which allows us to store a row directly into a record type variable from a query result. This method is useful for fetching specific rows and processing them efficiently.
Query:
DO
$$
DECLARE
rec1 record;
BEGIN
-- Select the employee
SELECT employee_id, full_name, manager_id
INTO rec1
FROM employees
WHERE employee_id = 13;
RAISE NOTICE '% - %(Manager id=%)', rec1.employee_id, rec1.full_name, rec1.manager_id;
END;
$$
LANGUAGE plpgsql;
Output

PostgreSQL Record type variable Example1
Explanation:
- Declaration: Declare the record type variable
rec1
.
- Assignment: Use the
SELECT
INTO
statement to select a row from the ‘employees'
table into rec1
where ‘employee_id'
is 13.
- Accessing Fields: Use dot notation to access the contents of ‘
rec1'
and print the information.
Example 2: Using Record Type Variables with FOR Loop
The following query shows how we can use record type variables in conjecture with the FOR loop statement. This allows iterating over multiple rows from a query result, with each row assigned to the record variable during each iteration, enabling dynamic row processing.
Query:
DO
$$
DECLARE
rec1 record;
BEGIN
FOR rec1 IN
SELECT employee_id, full_name
FROM employees
WHERE employee_id > 12
ORDER BY employee_id
LOOP
RAISE NOTICE '% - %', rec1.employee_id, rec1.full_name;
END LOOP;
END;
$$;
Output

PostgreSQL Record type variable Example2
Explanation:
- Declaration: Declare the record type variable ‘
rec1'
.
- FOR Loop: Use the
FOR
loop statement to iterate over the ‘employees'
table. In each iteration, assign a new row to ‘rec1'
.
- Accessing Fields: Use dot notation to access the contents of ‘
rec1'
and print the information for each iteration.
Important Points About PostgreSQL Record Type Variable
- Dynamic Structure: Record type variables do not have a predefined structure. Their structure is determined dynamically based on the row assigned to them.
- Dot Notation: We can access fields within a record type variable using dot (.) notation.
- Assignment Before Access: Ensure that the fields accessed within a record type variable are not NULL to avoid runtime errors.
- Local Scope: Record type variables are local to the PL/pgSQL block in which they are declared.
- Less Type-Safe: While record type variables offer flexibility, they are less type-safe compared to row type variables.
Conclusion
In this article, we have explained the dynamic nature of PostgreSQL record type variables, their declaration, and their usage in both SELECT INTO and FOR loops. These variables provide a flexible way to handle result sets where the structure is not predefined.
By using record type variables, we can process rows dynamically and efficiently in PL/pgSQL. Whether we are working with PostgreSQL SELECT INTO record or PostgreSQL record type with FOR loop, understanding how to use these variables is essential for dynamic SQL operations.
Similar Reads
PostgreSQL - Record type variable
In PostgreSQL, record-type variables provide a dynamic and flexible way to handle result sets that don't have a predefined structure. Unlike row-type variables, PostgreSQL record-type variables can change their structure after being assigned a new row, making them highly versatile for dynamic SQL op
5 min read
PostgreSQL - Row Type Variables
In PostgreSQL, row type variables are handy when you need to store a whole row of data returned by a query. They are particularly useful when dealing with SELECT INTO statements where the result contains multiple columns from a table or view. This feature simplifies handling data from complex querie
4 min read
PostgreSQL - Variables
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 faci
4 min read
PostgreSQL - VARCHAR Data Type
In the world of relational databases, PostgreSQL stands out with its robust support for various data types, including the flexible VARCHAR data type. This character data type allows us to store strings of variable length, making it an essential choice for many applications. In this article, we will
3 min read
PostgreSQL - SERIAL
When working with PostgreSQL, we need to create tables with unique primary keys. PostgreSQL offers a powerful feature known as the SERIAL pseudo-type which simplifies generating auto-incrementing sequences for columns. In this article, weâll learn about the PostgreSQL SERIAL pseudo-type by explain h
5 min read
PostgreSQL Tutorial
In this PostgreSQL tutorial youâll learn the basic data types(Boolean, char, text, time, int etc.), Querying and Filtering techniques like select, where, in, order by, etc. managing and modifying the tables in PostgreSQL. Weâll cover all the basic to advance concepts of PostgreSQL in this tutorial.
8 min read
PostgreSQL - TEXT Data Type
PostgreSQL provides a highly flexible character data type known as TEXT, designed to store character strings of virtually unlimited length. Unlike the VARCHAR data type, which can be limited to a specified length, the TEXT data type offers the same efficiency and performance without the length const
3 min read
PostgreSQL - TIME Data Type
In PostgreSQL, the TIME data type is essential for applications that require precise time tracking, such as scheduling systems and event logging. This data type allows for accurate time-based entries without storing date information. PostgreSQLâs TIME data type also supports fractional seconds for u
4 min read
PostgreSQL - Temporary Table
A PostgreSQL temporary table is a powerful tool for managing session-specific data that only needs to exist for a short duration. Temporary tables are created within a database session or transaction and are automatically dropped when the session ends, making them ideal for intermediate data storage
4 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE statement is used to define a new table within a database. It allows us to specify the table's structure, including column names, data types, and constraints, ensuring data integrity and consistency. Understanding the PostgreSQL table creation process is essential for
5 min read