PostgreSQL - Copying Data Types
Last Updated :
21 Aug, 2024
When working with PostgreSQL, you can define a variable that directly references the data type of a column in a table or the data type of another variable. This feature is useful when you want to maintain consistency and avoid repetitive changes to your code whenever the data type of a column is altered.
Let us better understand this concept in PostgreSQL along with syntax and examples.
Syntax to Reference Column Data Types
The below syntax refers to the data type of a column:
variable_name table_name.column_name%TYPE;
This syntax allows you to automatically copy the data type of the specified column into the variable.
Syntax to Reference Variable Data Types
The below syntax refers to the data type of another variable:
variable_name variable%TYPE;
This is useful when you need multiple variables of the same type, ensuring that any future changes in data type only need to be updated in one place.
Example
In this example, we will build a table (say, 'City') with a column (say, 'name') that has a CHAR data type and create a variable (say, 'city_name') and refer to the data type of the column as the data type of the variable.
city_name city.name%TYPE := 'Delhi';
Now let's check the data type of the variable
SELECT pg_typeof(city_name);
This will establish that the variable is of type CHAR.
By using copying type feature, you receive the following advantages:
- First, you don’t need to care about the data type of the column. You declare a variable to just hold the values of that column in a query.
- Second, when the data type of the column changes, you don’t need to change the variable declaration in the function to adapt to the new changes.
- Third, you can refer to the type of variables to the data type of function arguments to create polymorphic functions since the type of internal variables can change from one call to the next.
Assigning aliases to variables
PostgreSQL also allows you to assign aliases to variables, which can be particularly helpful in trigger procedures where variables have predetermined names such as NEW or OLD. You can create aliases to improve code readability:
new_name ALIAS FOR old_name;
This feature is mainly used in triggers to give more meaningful names to variables that represent data before or after an update.
Example: Using %TYPE and Aliases in a Trigger
CREATE OR REPLACE FUNCTION log_city_changes()
RETURNS TRIGGER AS $$
DECLARE
old_name ALIAS FOR OLD.name;
new_name ALIAS FOR NEW.name;
city_name City.name%TYPE;
BEGIN
city_name := new_name;
IF city_name IS DISTINCT FROM old_name THEN
INSERT INTO City_Logs (old_name, new_name, change_time)
VALUES (old_name, city_name, NOW());
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER city_update_trigger
AFTER UPDATE ON City
FOR EACH ROW EXECUTE FUNCTION log_city_changes();
In this example:
- The 'log_city_changes' function uses aliases to rename the 'OLD.name' and 'NEW.name' variables, making the code more readable.
- We also use the '%TYPE' feature to ensure that 'city_name' always matches the data type of the 'name' column in the 'City' table.
Similar Reads
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 DATEDIFF Function
PostgreSQL doesnât have a DATEDIFF function like some other databases, but you can still calculate the difference between dates using simple subtraction. This approach allows you to find out how many days, months, or years separate two dates. In this article, we'll explore how to compute date differ
6 min read
PostgreSQL - Data Types
PostgreSQL is a powerful, open-source relational database management system that supports a wide variety of data types. These data types are essential for defining the nature of the data stored in a database column. which allows developers to define, store, and manipulate data in a way that aligns w
5 min read
PostgreSQL - Psql commands
PostgreSQL, or Postgres, is an object-relational database management system that utilizes the SQL language. PSQL is a powerful interactive terminal for working with the PostgreSQL database. It enables users to execute queries efficiently and manage databases effectively.Here, we highlight some of th
2 min read
How to Dump and Restore PostgreSQL Database?
PostgreSQL remains among the most efficient and widely applied open-source relational database management systems. It provides the superior function of saving, configuring, and extracting information most effectively. In the process of migrating data, creating backups, or transferring databases betw
6 min read
Top 50 PostgreSQL Interview Questions and Answers
Are you preparing for a PostgreSQL interview? PostgreSQL is a powerful open-source relational database management system (RDBMS) that is well-known for its reliability, scalability, and rich set of features. Itâs a favorite among developers and businesses alike, making it essential to master if we w
15+ min read
PostgreSQL - Create Database
Creating a database in PostgreSQL is an important task for developers and database administrators to manage data effectively. PostgreSQL provides multiple ways to create a database, catering to different user preferences, whether through the command-line interface or using a graphical interface like
5 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 Connection String
A connection string is an essential component that enables applications to communicate with databases or other data sources by providing the necessary configuration details. It consolidates critical information such as the server address, database name, user credentials, and additional parameters li
4 min read
PostgreSQL - IF Statement
PostgreSQL IF statement is an essential tool for implementing conditional logic within SQL queries and stored procedures. It allows developers to execute different actions based on specific conditions and enhances the flexibility of database operations. In this article, we will explore various Postg
5 min read